需求:将某个普通类做为组件注册到容器中,可通过如下办法
1、定义HelloService类
package springboot_test.springboot_test.service;
public class HelloService {
}
2、定义配置类MyConfig.java
package springboot_test.springboot_test.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springboot_test.springboot_test.service.HelloService;
@Configuration
public class MyConfig {
//方法名称即为组件的id值
@Bean
public HelloService helloService(){
return new HelloService();
}
}
3、在原有测试类PersonTest.java中增加testHelloService()测试方法
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 springboot_test.springboot_test.SpringbootTestApplication;
import springboot_test.springboot_test.bean.Person;
@SpringBootTest(classes = SpringbootTestApplication.class)
@RunWith(SpringRunner.class)
public class PersonTest {
@Autowired
private Person person;
@Autowired
private ApplicationContext ac;
//在通过@Configuration和@Bean定义MyConfig.java之前,打印值为false,即容器中不存在helloService组件
//在配置之后,打印值为true
@Test
public void testHelloService(){
boolean flag =ac.containsBean("helloService");
System.out.println(flag);
}
@Test
public void getPerson(){
System.out.println(person);
}
}
0007SpringBoot中@Configuration与@Bean联合使用
原文:https://www.cnblogs.com/xiao1572662/p/11892826.html