@Resource example

来源:互联网 发布:监控端口号 编辑:程序博客网 时间:2024/05/19 22:52
<?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/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd"><context:annotation-config/><bean id="sexWomenList" class="com.vf.sample.SexWomenLister" ></bean><bean id="womenFinder" class="com.vf.sample.WomenFinder"><constructor-arg type="java.lang.String" value="Yan chen"></constructor-arg><constructor-arg type="int" value="19"></constructor-arg></bean><bean id="a" class="com.vf.sample.WomenFinder"><constructor-arg type="java.lang.String" value="Jia Yu"></constructor-arg><constructor-arg type="int" value="20"></constructor-arg></bean></beans>

package com.vf.sample;public class WomenFinder {/** * @param args */private String name;private int age;private final static String DEFAULT_NAME = "Maggie Q";private final static int DEFAULT_AGE = 18;public WomenFinder() {System.out.println("Copy that.I know how to find the correct women.");name = DEFAULT_NAME;age = DEFAULT_AGE;}public WomenFinder(String name,int age) {this.name = name;this.age = age;}@Overridepublic String toString() {return "Name: " + name + "\nAge: " + age;}}

package com.vf.sample;import javax.annotation.Resource;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;public class SexWomenLister {/** * @param args */private WomenFinder womenFinder;@Resource(name="a")public void setWomenFinder( WomenFinder womenFinder) {this.womenFinder = womenFinder;}public void print() {System.out.println(womenFinder.toString());}}


package com.vf.sample;


import org.springframework.context.ApplicationContext;


import org.springframework.context.support.ClassPathXmlApplicationContext;


public class Test {


/**
* @param args
*/

public static void main(String[] args) {

ApplicationContext apcx = (ApplicationContext) new ClassPathXmlApplicationContext("beans.xml");

SexWomenLister list = apcx.getBean("sexWomenList",SexWomenLister.class);
list.print();

}






}

Name: Jia Yu
Age: 20

原创粉丝点击