自動(dòng)配置注入 Bean
自動(dòng)配置的目的
為了使得 Bean 的注入不需要一個(gè)一個(gè)的配置,可以通過自動(dòng)配置來簡化。
自動(dòng)配置的實(shí)現(xiàn)
為創(chuàng)建為 Bean 的類添加注解
- @Component 一般用在身份不明確的組件上
- @Repository 一般用在數(shù)據(jù)庫訪問層--Dao層/Repository層
- @Service 一般用在業(yè)務(wù)邏輯層--Service層
- @Controller 一般用在控制器層--Controller層
示例
UserBean.java
@Component
public class UserBean {
private String name;
private int age;
@Override
public String toString() {
return "UserBean{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
UserService
@Service
public class UserService {
public void sayHello(){
System.out.println("userService");
}
}
配置包掃描
如果由多個(gè)包需要掃描,多個(gè)包可以使用,隔開
在包掃描時(shí),設(shè)置屬性use-default-filters,可以按照注解過濾掃描的類
- true 結(jié)合 exclude-filter 標(biāo)簽使用,表示去除某個(gè)注解
- fase 結(jié)合 include-filter 標(biāo)簽使用,表示包含某個(gè)注解
XML 配置包掃描示例
xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="org.daistudy" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
</context:component-scan>
</beans>
應(yīng)用
ClassPathXmlApplicationContext context = new
ClassPathXmlApplicationContext("applicationContext.xml");UserBean userBean = (UserBean) context.getBean("userBean");System.out.println(userBean);
Java 配置包掃描示例
java配置
@Configuration
@ComponentScan(value = "org.daistudy", useDefaultFilters = false, includeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION, value = Service.class)
})
public class JavaConfig {
}
應(yīng)用
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("org.daistudy.config");
UserBean userBean = (UserBean) context.getBean("userBean");
System.out.println(userBean);
UserService userService = context.getBean(UserService.class);
userService.sayHello();
結(jié)果
Spring 容器中沒有 userBean 的 Bean,有 userService 的 Bean。