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

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

最新文章

  1. 多功能弹窗控件layer
  2. 优化MySQL数据库性能的八大方法
  3. sscanf函数和正则表达式
  4. Rest接口中正则表达式
  5. Python 获取 网卡 MAC 地址
  6. ListView 连接数据库的增删改查
  7. HTML5之图像处理
  8. java操作mongodb——插入数据
  9. 个人作业-2 英语学习APP分析
  10. Android Scheme协议与应用全解析
  11. Apache Tomcat Eclipse Integration
  12. 【BZOJ5308】[ZJOI2018]胖(模拟,ST表,二分)
  13. vue 3D小球 loading
  14. POJ1013 称硬币
  15. 常见面试算法题JS实现-仅用递归函数和栈操作逆序一个栈
  16. iOS:UIView视图与组件控件
  17. map reduce相关程序
  18. CF311B Cats Transport 斜率优化DP
  19. POJ3347:Kadj Squares——题解
  20. InputArray和OutputArray

热门文章

  1. 【ARM-Linux开发】如何使用opkg在RicoBoard上在线安装软件包
  2. windows服务器入门 php的安装
  3. [转载]桥接与NAT
  4. Java面试 - 在Java中, 既然构造方法是一个方法,那么为什么不使用void 定义呢?
  5. 数据库数据生成Excel表格(多用在导出数据)
  6. java源码 -- TreeSet
  7. LC 144. / 94. / 145. Binary Tree Preorder/ Inorder/ PostOrder Traversal
  8. Golang不会自动把slice转换成interface{}类型的slice
  9. java——内存中的数组
  10. MongoDB操作-备份和恢复