WordPress开发app,福州seo网站推广优化,小程序免费制作平台源码,甘肃最新消息今天Bean配置类的注解开发
Component等注解替代了bean标签#xff0c;但像import、context:componentScan等非bean标签怎样去使用注解去替代呢#xff1f;定义一个配置类替代原有的xml配置文件#xff0c;bean标签以外的标签#xff…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 resourceclasspath: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-packagecom.example/
ComponentScan({com.example})
// context:property-placeholder locationjdbc.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));}
}