介绍
在springboot中,提倡使用 配置类 替代 spring xml配置文件
参见:spring @Configuration替代application-config.xml
配置类要用 @Configuration 注解修饰
应用场景
假设有 Service 类,该类是 其他人写的,并且此人不允许我们改动代码
我们如果想将此 Service 类注入到 Controller 中,就需要在该 Service 类加上 @Service 注解,但问题是不允许我们改动,此时就可以使用 @Configuration 和 @Bean
源代码
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
@AliasFor(
annotation = Component.class
)
String value() default "";
boolean proxyBeanMethods() default true;
}
使用方法
修饰类
多搭配 @Bean 注解,用于注册 Bean
作用
表示该类是 配置类
在spring框架中替代 spring.xml 配置文件
在springboot中,没有 xml 配置文件,但 集成 第三方框架时,又需要进行配置,此时可用该注解
配置类的要求
- 不可以是final类;
- 不可以是匿名类;
- 嵌套的配置类必须是静态类。
总之一句话:将一个普通的干净的类作为配置类,最为稳妥
案例
springboot @Configuration注解和配置类、@Bean案例