5. 基于注解的Spring应用 - Bean 配置类的注解开发

68 阅读1分钟

@Component等注解替代了<bean>标签,但是像<import><context:componentScan> 等非 <bean> 标签怎样去使用注解替代呢?

答: 定义一个配置类替代原有的xml配置文件, <bean>标签以外的标签, 一般都是在配置类上使用注解完成的

<!-- 加载properties文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>

<!-- 组件扫描 -->
<context:component-scan base-package="com.itheima"/>

<!-- 引入其他xml文件 -->
<import resource="classpath:beans.xml"/>
  • @Configuration注解标识的类为配置类,替代原有 xml 配置文件,该注解

第一个作用是标识该类是一个配置类,

第二个作用是具备 @Component 作用

@Configuration
public class ApplicationContextConfig{}
  • @ComponentScan 组件扫描配置,替代原有 xml 文件中的 <context:component-scan base-package=""/> 配置
@Configuration
@ComponentScan({"com.itheima.service","com.itheima.dao"})
public class ApplicationContextConfig{}
base-package 的配置方式:
1. 指定一个或多个包名:扫描指定包及其子包下使用注解的类
2. 不配置包名:扫描当前 **@componentScan** 注解配置类所在包及其子包下的类
  • @PropertySource 注解用于加载外部 properties 资源配置,替代原有 xml 中的<context :property-placeholder location=""/> 配置
@Configuration
@ComponentScan({"com.itheima.service","com.itheima.dao"})
@PropertySource({"classpath:jdbc.properties","classpath:xxx.properties"})
public class ApplicationContextConfig{}
  • @Import 用于加载其他配置类,替代原有 xml 中的 <import resource="classpath:beans.xml"/> 配置
@Configuration
@ComponentScan({"com.itheima.service","com.itheima.dao"})
@PropertySource({"classpath:jdbc.properties","classpath:xxx.properties"})
@Import(OtherConfig.class)
public class ApplicationContextConfig{}