spring自动注入入门

来源:互联网 发布:python是开源的吗 编辑:程序博客网 时间:2024/06/05 20:10

spring配置文件beans.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 /><context:component-scan base-package="*"/></beans>

接口

package test;public interface Man {String sayHello();}
实现类

package test;import org.springframework.stereotype.Component;@Component("chinese")public class Chinese implements Man{private String message;public Chinese(){this.message="fdsafsd";}@Overridepublic String sayHello() {return this.message;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}}

测试类:

package test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import org.springframework.stereotype.Component;@Component("aaaabbbb")public class Main {@Autowired@Qualifier("chinese")private Man man;public static void main(String[] args) {ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");Main main = (Main)ctx.getBean("aaaabbbb");Chinese cc = (Chinese)main.getMan();cc.setMessage("aaaaaaaaaa");System.out.println(main.getMan().sayHello());}public Man getMan(){return this.man;}}



0 0