每天一个SpringBoot注解之@Configuration
先按照简单代码示例注解的作用,最后再做一个总结。
从Spring3.0,@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。
1.先看看最简单的应用,我们创建一个类,加上Configuration注解
@Configuration
public class ConfigurationTest {
public ConfigurationTest() {
System.out.println("TestConfiguration容器启动初始化。。。");
}
}
然后启动主程序,让我们看看输出,很明显,只要加上了这个注解,就可以启动spring容器
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.4.1)
2021-01-12 20:13:46.018 INFO 35216 --- [ main] com.example.demo.DemoApplication : Starting DemoApplication using Java 1.8.0_211 on DESKTOP-AD5JM34 with PID 35216 (D:\Idea\workspace\demo\target\classes started by dell in D:\Idea\workspace\demo)
2021-01-12 20:13:46.022 INFO 35216 --- [ main] com.example.demo.DemoApplication : No active profile set, falling back to default profiles: default
2021-01-12 20:13:46.801 INFO 35216 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-01-12 20:13:46.809 INFO 35216 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-01-12 20:13:46.809 INFO 35216 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.41]
2021-01-12 20:13:46.876 INFO 35216 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-01-12 20:13:46.876 INFO 35216 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 808 ms
TestConfiguration容器启动初始化。。。
2.我们再结合@Bean注解来加载对象,新建一个TestBean对象
public class TestBean {
private String username;
private String url;
private String password;
public void sayHello() {
System.out.println("TestBean sayHello...");
}
public String toString() {
return "username:" + this.username + ",url:" + this.url + ",password:" + this.password;
}
public void start() {
System.out.println("TestBean 初始化。。。");
}
public void cleanUp() {
System.out.println("TestBean 销毁。。。");
}
}
这次我们直接在刚刚的类里面用main方法来测试,而不是项目的启动类
@Configuration
public class ConfigurationTest {
public ConfigurationTest() {
System.out.println("TestConfiguration容器启动初始化。。。");
}
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(ConfigurationTest.class);
TestBean testBean = context.getBean(TestBean.class);
testBean.sayHello();
}
@Bean
@Scope("prototype")
public TestBean testBean() {
return new TestBean();
}
}
当启动main方法后,我们来看看输出
很明显,对象创建好了,而且sayHello方法也能正常调用
20:18:20.699 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'configurationTest'
TestConfiguration容器启动初始化。。。
20:18:20.704 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'testBean2'
TestBean sayHello...
当然@Bean还可以加其他参数
我们可以加上name(不指定就是方法名同名),destroyMethod ,initMethod 方法,指定为我们刚刚创建的对象中TestBean 中的方法
@Bean(name = "TestBean",destroyMethod = "cleanUp",initMethod = "start")
@Scope("prototype")
public TestBean testBean() {
return new TestBean();
}
让我们再看看输出
20:21:07.822 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'configurationTest'
TestConfiguration容器启动初始化。。。
TestBean 初始化。。。
TestBean sayHello..
@Bean注解默认作用域为单例singleton作用域,可通过@Scope(“prototype”)设置为原型作用域
3.我们可以用@Configuration配合@Component注册一个Bean
我们为对象加上@Component注解
@Component
public class TestBean {
private String username;
private String url;
private String password;
public void sayHello() {
System.out.println("TestBean sayHello...");
}
public String toString() {
return "username:" + this.username + ",url:" + this.url + ",password:" + this.password;
}
public void start() {
System.out.println("TestBean 初始化。。。");
}
public void cleanUp() {
System.out.println("TestBean 销毁。。。");
}
}
然后再@Configuration注解的类中加上@ComponentScan
@Configuration
@ComponentScan(basePackages = "com.example.demo.configuration")
public class ConfigurationTest {
public ConfigurationTest() {
System.out.println("TestConfiguration容器启动初始化。。。");
}
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(ConfigurationTest.class);
TestBean testBean = context.getBean(TestBean.class);
testBean.sayHello();
}
// @Bean(name = "TestBean",destroyMethod = "cleanUp",initMethod = "start")
// @Scope("prototype")
// public TestBean testBean() {
// return new TestBean();
// }
}
看看输出,仍然没有问题
20:24:41.892 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'configurationTest'
TestConfiguration容器启动初始化。。。
20:24:41.902 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'testBean'
TestBean sayHello...
最后总结一下,相比于SSM的xml
@Configuation等价于<Beans></Beans>
@Bean等价于<Bean></Bean>
@ComponentScan等价于<context:component-scan base-package="com.dxz.demo"/>
本文地址:https://blog.csdn.net/StreamlineWq/article/details/112546214
推荐阅读
-
springboot系列之03-使用IDEA完成第一个示例程序
-
JAVA WEB快速入门之从编写一个基于SpringBoot+Mybatis快速创建的REST API项目了解SpringBoot、SpringMVC REST API、Mybatis等相关知识
-
浅谈基于SpringBoot实现一个简单的权限控制注解
-
springboot之mybatis注解形式
-
每天一个Linux命令之shell单引号和双引号的经典解释
-
源码系列【springboot之@Import注解多个类引入同一个类源码解析】
-
Java基础知识之注解(Annotation)及纯java代码在数据库中创建一个表
-
SpringBoot整合定时任务----Scheduled注解实现(一个注解全解决)
-
springboot之additional-spring-configuration-metadata.json自定义提示
-
每天学一个 Linux 命令之more命令