0006SpringBoot中@Configuration与@Bean联合使用
2024-08-29 21:35:46
需求:将某个普通类做为组件注册到容器中,可通过如下办法
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);
}
}
最新文章
- 多功能弹窗控件layer
- 优化MySQL数据库性能的八大方法
- sscanf函数和正则表达式
- Rest接口中正则表达式
- Python 获取 网卡 MAC 地址
- ListView 连接数据库的增删改查
- HTML5之图像处理
- java操作mongodb——插入数据
- 个人作业-2 英语学习APP分析
- Android Scheme协议与应用全解析
- Apache Tomcat Eclipse Integration
- 【BZOJ5308】[ZJOI2018]胖(模拟,ST表,二分)
- vue 3D小球 loading
- POJ1013 称硬币
- 常见面试算法题JS实现-仅用递归函数和栈操作逆序一个栈
- iOS:UIView视图与组件控件
- map reduce相关程序
- CF311B Cats Transport 斜率优化DP
- POJ3347:Kadj Squares——题解
- InputArray和OutputArray
热门文章
- 【ARM-Linux开发】如何使用opkg在RicoBoard上在线安装软件包
- windows服务器入门 php的安装
- [转载]桥接与NAT
- Java面试 - 在Java中, 既然构造方法是一个方法,那么为什么不使用void 定义呢?
- 数据库数据生成Excel表格(多用在导出数据)
- java源码 -- TreeSet
- LC 144. / 94. / 145. Binary Tree Preorder/ Inorder/ PostOrder Traversal
- Golang不会自动把slice转换成interface{}类型的slice
- java——内存中的数组
- MongoDB操作-备份和恢复