文章出處

上一篇繼續, 學習了基本的注入使用后,可能有人會跟我一樣覺得有點不爽,Programmer的每個Field,至少要有一個setter,這樣spring配置文件中才能用<property>...</property>來注入. 能否不要這些setter方法? 答案是Yes

一、為Spring配置文件,添加annotation支持,以及 default-autowire屬性

<?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"
       default-autowire="byName">

    <context:annotation-config/>

    <bean id="jimmy" class="com.cnblogs.yjmyzz.domain.Programmer"/>

    <bean id="computerlist" class="java.util.ArrayList">
        <constructor-arg>
            <list>
                <bean class="com.cnblogs.yjmyzz.domain.MacBook"/>
                <bean id="t60" class="com.cnblogs.yjmyzz.domain.ThinkPad"/>
            </list>
        </constructor-arg>
    </bean>

    <bean id="wangcai" class="com.cnblogs.yjmyzz.domain.Dog"/>

    <bean id="jimmy_name" class="java.lang.String">
        <constructor-arg>
            <value>jimmy.yang</value>
        </constructor-arg>
    </bean>

</beans>

 注: 相對原來的版本,有幾個小變化:

a) 最開始的xml聲明部分,添加了xmlns:context

b) default-autowired設置為byName,運行時,將通過配置文件中,bean的id/name,來實現自動注入(后面會有代碼演示)

c) 添加了<context:annotation-config/> ,這表明Spring允許在java類中,可以通過在field成員上,通過注解自動注入,而不再需要在配置文件中,手動指定property注入

d) 名為jimmy的bean,去掉<property>...</property>的注入配置

那么,問題來了,運行時,jimmy如何得到name,pet,computers這些屬性的實例呢?

 

二、使用@Resource自動注入

Spring支持好幾種注解自動注入,比如@Inject,@Resource,@Autowired,這里只演示@Resource這一種

package com.cnblogs.yjmyzz.domain;
import javax.annotation.Resource;

import java.util.List;
public class Programmer {

    @Resource(name = "jimmy_name")
    private String name;

    @Resource(name = "wangcai")
    private Pet pet;

    @Resource(name = "computerlist")
    private List<Computer> computers;


    public void show() {
        System.out.print("My name is " + name);
        System.out.print(", and I have " + computers.size() + " computer" + (computers.size() > 1 ? "s" : "") + ":");
        System.out.println();
        for (Computer c : computers) {
            c.showInfo();
        }
        System.out.println("And I have a pet, everyday,when I go home, it will welcome me by  ");
        pet.welcomeMeToHome();

    }
}

對比原來的版本,去掉了所有的setter,整個類看上去非常清爽,@Resouce后的name=XXX,這里的XXX要跟Spring配置文件中,bean的id一致

 

未完待續...

屬性文件的使用,明天有空再來補上


文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()