sping框架纯注解配置

时间:2021-01-18 21:59:56

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:用于指定其它配置类的字节码,即:配置类.class

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

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

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

@Autowired
private Date creatDate;

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

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

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 {

}

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();
}