首页 > 编程语言 > 详细

0007SpringBoot中@Configuration与@Bean联合使用

时间:2019-11-19 22:31:57      阅读:93      评论:0      收藏:0      [点我收藏+]

需求:将某个普通类做为组件注册到容器中,可通过如下办法

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!