1.写需要注解注入的类:
Propertie.java
package study;
public class Propertie {
public void show() {
System.out.print("我是注解注入的!");
}
}
2.Person接口:
package study;
public interface Person {
public void output();
}
3.Chinese实现Person接口:
package study;
//必要的包
import javax.annotation.Resource;
public class Chinese implements Person {
//注解注入符合@Resource
@Resource private Propertie p;
private String name;
public void output() {
p.show();
}
}
4.测试类TestPerson.java
package study;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestPerson {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean3.xml");
Person p = (Person) ctx.getBean("chinese");
p.output();
}
}
5.bean3.xml配置文件
<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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
<bean id="p" class="study.Propertie">
</bean>
<bean id="chinese" class="study.Chin
ese">
<property name="name">
<value>张敏鹏</value>
</property>
</bean>
</beans>
<!--
注解所引用的:
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation=" http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
-->
6.运行结果: