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

相關文章
相關標籤/搜索