0006SpringBoot中@Configuration與@Bean聯合使用


需求:將某個普通類做為組件注冊到容器中,可通過如下辦法

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);
}
}




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM