Spring_2023_11_21_1 使用javaConfig实现DI

发布时间 2023-11-21 11:29:29作者: Kbaor

Spring_Aop 2023_11_21_1

使用javaConfig实现DI

javaConfig,是在 Spring 3.0 开始从一个独立的项目并入到 Spring 中的。javaConfig 可以看成一个用于完成 Bean 装配的 Spring 配置文件,即 Spring 容器,只不过该容器不是 XML文件,而是由程序员使用 java 自己编写的 java 类。
一个类中只要标注了@Configuration注解,这个类就可以为spring容器提供Bean定义的信息了,或者说这个类就成为一个spring容器了。
标注了@Configuration和标注了@Component的类一样是一个Bean,可以被Spring的 context:component-scan 标签扫描到。类中的每个标注了@Bean的方法都相当于提供了一个Bean的定义信息。

MySpringConfig

package com.bboy.config;

import com.bboy.dao.StudentDao;
import com.bboy.dao.impl.StudentDaoImpl;
import com.bboy.pojo.Student;
import com.bboy.service.StudentService;
import com.bboy.service.impl.StudentServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @类描述:
 * @作者:秦帅
 * @时间:2023/11/21 0021 9:13:53
 */
//-:标注此类为spring的配置类,等同于Spring  xml 核心配置文件
@Configuration

public class MySpringConfig {
//  @ Bean 等同于<bean />
    @Bean
    public Student student(){
        Student student = new Student();
        //-:属性的注入
        student.setAge(20);
        student.setName("秦帅");
        student.setSex("男");
        return student;
    }
    @Bean
    public StudentDao studentDao (){
        StudentDao studentDao = new StudentDaoImpl();
        return studentDao;
    }
    @Bean
    public StudentService studentService(){
        StudentServiceImpl studentService = new StudentServiceImpl();
        studentService.setStudentDao(studentDao());
        return studentService;
    }
}

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!--
       进行组件扫描,扫描含有注解的类
   -->
    <context:component-scan base-package="com.bboy.config"/>
</beans>