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