1. 程式人生 > 實用技巧 >Spring--->Bean的自動裝配

Spring--->Bean的自動裝配

  • 自動裝配是Spring滿足Bean以來的一種方式
  • Spring會在上下文自動尋找,並自動給bean裝配屬性

在Spring中有三種裝配方式

  1. 在xml中顯示的配置
  2. 在Java中的顯示配置
  3. 隱式的自動裝配bean【重點】

1、自動裝配(xml顯示配置)

    <bean name="dog" class="com.xian.pojo.Dog"></bean>
    <bean name="cat" class="com.xian.pojo.Cat"></bean>
    <bean name="person" class="com.xian.pojo.Person" autowire="byName">
       <property name="name" value="people"/>
    </bean>

Byname:會自動在容器上下文找,和自己set方法後面對應的beanid

ByType:會自動在容器上下文找,和自己物件屬性對應的bean

   <bean name="dog" class="com.xian.pojo.Dog"></bean>
    <bean name="cat" class="com.xian.pojo.Cat"></bean>
    <bean name="person" class="com.xian.pojo.Person" autowire="byType">
       <property name="name" value="people"/>
    </bean>

2、使用註解完成自動裝配(隱形配置)

注意新增功能<context:annotation-config/>

beans.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:annotation-config/> <bean name="dog22" class="com.xian.pojo.Dog"></bean> <bean name="cat" class="com.xian.pojo.Cat"></bean> <bean name="person" class="com.xian.pojo.Person"> <property name="name" value="hanhan"/> </bean> </beans>

@Autowired(@Nullable =false 允許欄位為null)

@Qualifier(value="dog22") 指定bean

public class Person {
    @Autowired
    private Cat cat;
    @Autowired
    private Dog dog;
    private String name;}

可以在屬性上使用,也可以在set方法上使用

@Resource註解

public class Person {
    @Resource
    private Cat cat;
   @Resource
    private Dog dog;
    private String name;
}

@Autowired、@Resource註解的區別

  • 都是用來自動裝配的,都可以放在屬性欄位身上
  • @Autowired是通過ByType的方式實現的,而且必須要求這個物件存在

  • @Resource預設通過ByName的方式實現的,如果找不到名字,則通過ByType的方式

  • 執行循序不同,

3、Config配置檔案【重點】(Java顯示配置)

配置檔案加入@Configuration,對應的Bean加入@Bean

@Configuration
//這個也會被Spring容器託管,註冊到容器中因為它本省就是一個@Component
//@Configration本身就是一個配置類,和Beans.xml是一樣的
@ComponentScan("com.xian.dao")
public class Config {
    //註冊一個Bean就相當於之前的一個Bean標籤
    //這個方法的名字就是Bean標籤中的ID屬性
    //方法的返回值就相當於bean標籤當中的class屬性
    @Bean
    public User getuser(){
        return new User();
    }
}

普通類

類中只進行值得注入@Component(開啟服務)@Value("hanhanhan")

@Component
public class User {
    // @Value等價於<property name="name" value="hanh"/>

    public String name;

    public String getName() {
        return name;
    }
    @Value("hanhanhan")
    public void setName(String name) {
        this.name = name;
    }
}

Test

 public void TestConfig(){
        ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
        User getuser = context.getBean("getuser",User.class);
        System.out.println(getuser.getName());
    }