Spring IoC/DI 08-自動(dòng)配置注入 Bean

自動(dòng)配置注入 Bean

自動(dòng)配置的目的

為了使得 Bean 的注入不需要一個(gè)一個(gè)的配置,可以通過自動(dòng)配置來簡化。

自動(dòng)配置的實(shí)現(xiàn)

為創(chuàng)建為 Bean 的類添加注解

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

配置包掃描

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

在包掃描時(shí),設(shè)置屬性use-default-filters,可以按照注解過濾掃描的類

  1. true 結(jié)合 exclude-filter 標(biāo)簽使用,表示去除某個(gè)注解
  2. 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。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容