IOC容器基于Bean管理的完全注解开发放弃配置文件
通过注解的方式,我们不需要在xml配置文件里进行各种注入配置,只需要开启扫描即可。
那如果开启扫描也能通过注解方式,那不就完全不需要配置文件了么?
创建配置类
创建配置类,替代 xml 配置文件。
1
2
3
4
5
6
7
|
package com.pingguo.spring5.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan (basePackages = { "com.pingguo.spring5" }) public class SpringConfig { } |
配置类中需要注意的:
@Configuration:类名你可以随便起,但是想让spring识别出这是配置类,需要加这个注解。
@ComponentScan:这个注解就是扫描用,后面参数值是你指定的路径。
测试一下
之前测试函数里是读取配置文件的,现在我把配置文件删掉了,要怎么处理?
1
2
3
4
5
6
7
8
9
10
|
public class TestService { @Test public void testService() { ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig. class ); UserService userService = context.getBean( "userService" , UserService. class ); System.out.println(userService); userService.add(); } } |
就是使用 AnnotationConfigApplicationContext,后面括号里是配置类。
其他几个层的类代码都不变,并且已经删掉xml配置文件了。
现在运行测试方法:
1
2
3
4
5
|
com.pingguo.spring5.service.UserService @72a7c7e0 service add() ... ... spring 从 0 开始 UserDao UserDaoImpl2 add()... ... Process finished with exit code 0 |
运行正常,结果与之前使用xml配置文件时一致。
不过这种完全注解开发,在实际操作中是用到另一种结构,就是spring boot 。
虽然 springboot 我之前就有过一些学习,但就是个入门都不到,很多东西能用但不知道为什么。就拿这些注解来说,学了spring 我才知道的清楚些。所以,待 spring 学完,就开启 springboot 学习,更多关于Spring IOC Bean管理的资料请关注服务器之家其它相关文章!
原文链接:https://blog.csdn.net/wessonlan/article/details/124812968