目录
使用SpringBoot推荐的全注解方式添加组件(JavaConfig)
现在一般不使用传统的XML文件配置添加组件,而是使用就是注解方式(JavaConfig方式)添加组件
SpringBoot使用传统的XML配置文件添加组件
创建beans.xml文件,如下(类已经存在)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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">
<bean id="dog" class="com.test.yml.Dog"></bean>
<bean id="person" class="com.test.yml.Person">
<property name="dog" ref="dog"></property>
</bean>
</beans>
SpringBoot加入beans.xml,bean在resource目录下
在项目启动类中添加@ImportResource注解,将beans文件添加进来,并启动此类
在SpringBoot项目测试
package com.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;
import com.test.yml.Person;
@RunWith(SpringRunner.class)
@SpringBootTest
public class Test1 {
@Autowired
Person person;
@Autowired
ApplicationContext ac;
@Test
public void contextLoads() {
boolean isE = ac.containsBean("dog");
Person person2 = ac.getBean(Person.class);
System.out.println(isE);
System.out.println(person.getDog());
System.out.println(person2.getDog());
}
}
两种方式都可以从容器中拿到对象
此方式返回true,则证明添加容器成功
运行结果(说明组件被添加到容器中了)
使用SpringBoot推荐的全注解方式添加组件(JavaConfig)
1、配置类==Spring配置文件,@Configuration修饰类用来指明当前类是一个配置类,用来替代Spring配置文件(类似<bean>)
2、使用@Bean给容器中添加组件(类似<bean 中的 class="xxx" 方法名就是id="xx")
使用全注解方式改造上面的XML方式(方法名就是组件的id)
改造成注解方式
package com.test.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.test.yml.Dog;
import com.test.yml.Person;
/**
* 功能:加入这个注解@Configuration让该类成为配置类(相当于XML配置文件)
* 相当于<bean>
* @author xuexue
*
*
*/
@Configuration
public class MyAppConfig {
//@Bean添加到容器中;容器中这个组件默认的id就是方法名
@Bean
public Person person() {
Person person = new Person();
person.setDog(dog());
return person;
}
@Bean
public Dog dog() {
return new Dog();
}
}
将启动类的XML方式注释掉
运行结果,与XML方式一致(在测试目录中测试,不需要启动主程序类)