Spring IoC/DI 08-自動配置注入 Bean

自動配置注入 Bean

自動配置的目的

爲了使得 Bean 的注入不需要一個一個的配置,可以通過自動配置來簡化。

自動配置的實現

爲創建爲 Bean 的類添加註解

  1. @Component 一般用在身份不明確的組件上
  2. @Repository 一般用在數據庫訪問層–Dao層/Repository層
  3. @Service 一般用在業務邏輯層–Service層
  4. @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");
    }
}

配置包掃描

如果由多個包需要掃描,多個包可以使用,隔開

在包掃描時,設置屬性use-default-filters,可以按照註解過濾掃描的類

  1. true 結合 exclude-filter 標籤使用,表示去除某個註解
  2. fase 結合 include-filter 標籤使用,表示包含某個註解

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>

應用

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 {
}

應用

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

結果

Spring 容器中沒有 userBean 的 Bean,有 userService 的 Bean。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章