sping框架纯注解配置

1.相关注解
①@Configuration注解-->添加了该注解在类上,就代表该类是spring的配置类。该类的做用是用来替代原来的XML配置文件的。
经过配置类建立容器时,须要使用AnnotationConfigApplicationCpntext(有@Configuration注解的类.class)来获取对象。
②ComponentScan注解-->注解扫描,用于扫描spring组件类的路径,等同于原来配置文件的<context:component-scan base-package="com.boya"/>
属性:basePackage:用于指定须要扫描的包,和该注解的value属性做用同样。
③@propertySource注解-->用于加载.properties文件中的配置。至关于<context:property-placeholder file-encoding="UTF-8" location="classpath:CustomerContent"/>
属性:value:用于指定properties文件的位置,若是是在类路径下,须要写上classpath:
④@Bean注解--> 这个注解只能放在方法上,使用此方法建立一个对象放入spring容器中,至关于XML配置中的<bean>标签,对于一些没有办法加上组件注解的类,咱们能够经过@Bean注解将他加入到容器里面
属性:name:给当前@Bean注解方法建立的对象指定一个名称(即bean的id)。
⑤@import注解-->做用:用于导入其余配置类,在引入其余配置类时,能够不用再写@Configuration注解。固然,写上也没问题。
属性:value:用于指定其它配置类的字节码,即:配置类.classspring

2.实现纯注解配置
1.建立一个需配置的类
@Component
public class Customer {

@Value("${customer.name}")
private String name;测试

@Value("${customer.age}")
private int age;this

@Autowired
private Date creatDate;

public void setName(String name) {
this.name = name;
}spa

public void setAge(int age) {
this.age = age;
}prototype

public void setCreatDate(Date creatDate) {
this.creatDate = creatDate;
}

public void show() {
System.out.println("名字:"+name+"年龄:"+age+"日期:"+creatDate);
}
}

2.config配置类
@Configuration
public class Config {

@Scope(value="prototype")
@Bean(name="date")
public Date getDate() {
return new Date();
}
}

3.主配置类
//申明该类是一个配置类
@Configuration
//扫描注解,至关于配置文件<context:component-scan base-package="cn.boya"></context:component-scan>
@ComponentScan(value="cn.boya")
//添加文件,至关于配置文件<context:property-placeholder file-encoding="UTF-8" location="classpath:CustomerContent"/>
@PropertySource(encoding="UTF-8",value="classpath:CustomerContent")
//导入其它配置一块儿
@Import(value=Config.class)
public class ApplicationContextConfig {

}component


4.测试类
@Test
public void show(){
//ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring.xml");
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ApplicationContextConfig.class);
Customer customer = context.getBean("customer", Customer.class);
customer.show();
context.close();
}xml

相关文章
相关标签/搜索