需求:將某個普通類做為組件注冊到容器中,可通過如下辦法
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);
}
}