spring @Configuration、@ComponentScan替代spring.xml

介绍

Spring3.0提出注解@Configuration替代application-config.xml配置文件

好处

  1. 使用纯java代码,不在需要xml

  2. 在配置中也可享受OO带来的好处

  3. 类型安全对重构也能提供良好的支持

  4. 依旧能享受到所有springIoC容器提供的功能

@Configuration 注解

使用方法

修饰类

作用

表示该类是 配置类,相当于spring配置文件 spring.xml

@ComponentScan

使用

修饰类方法

作用

指定要扫描某包下的注解

例子:传统方式

使用spring的传统方式,一般有spring.xml配置文件,如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="UserSrvImpl" class="top.malaoshi.UserSrvImpl" scope="singleton">
    <property name="dao" ref="UserDao"></property>
</bean>
    <bean id="UserDao" class="top.malaoshi.UserDao">
    </bean>
</beans>

执行

public class Main {
    public static void main(String[] args) {
        ApplicationContext ac=new ClassPathXmlApplicationContext("spring.xml");

        IUserService srv=(IUserService)ac.getBean("UserSrvImpl");
    }
}

例子:注解方式

@Configuration
@ComponentScan("top.malaoshi")//指定扫描该包下的注解
public class ApplicationConfig {

}

配置类的要求

配置类有如下要求:

  1. 不可以是final类型;
  2. 不可以是匿名类;
  3. 嵌套的配置类必须是静态类。

总之一句话:将一个普通的干净的类作为配置类,最为稳妥

java代码使用

ApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationConfig.class);  
OrderService orderService = ctx.getBean(OrderService.class);

感谢:
https://blog.csdn.net/H12KJGJ/article/details/80670704