Bean配置类的注解开发
- @Component等注解替代了<bean>标签,但像<import>、<context:componentScan>等非<bean>标签怎样去使用注解去替代呢?定义一个配置类替代原有的xml配置文件,<bean>标签以外的标签,一般都是在配置类上使用注解完成的。
- @Configuration注解标识的类为配置类,替代原有的xml配置文件,该注解的第一个作用是标识该类是一个配置类,第二个作用是具备@Component注解的作用,将该配置类交给Spring容器管理
- @ComponentScan组件扫描配置,替代原有的xml文件中的<context:component-scan base-package=""/>
- base-package的配置方式
- 指定一个或者多个包名:扫描指定包及其子包下使用的注解类
- 不配置包名:扫描当前@ComponentScan注解配置类所在包及其子包的类
- @PropertySource注解用于加载外部properties资源配置,替代原有xml文件中的 <context:property-placeholder location=""/>配置
- @Import用于加载其它配置类,替代原有xml中的<import resource="classpath:bean.xml"/>配置
- 具体示例代码如下
-
package com.example.Configure;import com.example.Beans.otherBeans; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.PropertySource;@Configuration // todo 标注当前类是一个配置类(替代配置文件)、其中包含@Compoent注解 // <context:component-scan base-package="com.example"/> @ComponentScan({"com.example"}) // <context:property-placeholder location="jdbc.properties"/> @PropertySource("jdbc.properties") // <import resource=""/> @Import(otherBeans.class) public class SpringConfig {}
-
小结
- 创建配置类作用其实就是用来替代配置文件的作用,xml配置文件中的不同标签都在配置类中用对应的注解进行替代,由此获取Spring容器的方式也会发生变化,由之前的xml方式获取Spring核心容器变为通过注解的方式加载Spring容器的核心配置类。
-
package com.example.Test;import com.example.Configure.SpringConfig; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class TestApplicationContext {public static void main(String[] args) {// xml方式加载Spring容器的核心配置文件// ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");// 注解方式加载Spring容器的核心配置类ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);System.out.println(context.getBean("dataSource"));} }
-