Spring@autowired注解
第一步:
我们先要有一个类,在这个类中定义几个方法
代码如下:
package com.huweiyang;
publicclassA {
public A(){
System.out.println("我是A类的构造方法");
}
publicvoid add(){
System.out.println("我是A类的add方法");
}
}
第二步:
我们要有一个bean,Spring容器就是用来管理bean的所以他使用的注解也离不开bean,在bean中定义一个A类类型的变量,并给它set和get方法
代码如下:
package com.huweiyang;
import org.springframework.beans.factory.annotation.Autowired;
publicclassB {
@Autowired
private A a;
public A getA() {
a.add();
returna;
}
publicvoid setA(A a) {
this.a = a;
}
}
第三步:
我们需要来配置xml,因为我们使用了@autwired注解的方式来注入,而spring中不支持自动注解的注入的功能,所以我们需要在xml文件中启动注解的功能并指定路径。
启动注解功能的属性是:<context-annotation-config/>
代码如下:
<?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.xsd
http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 启动注解功能 -->
<context:annotation-config />
<bean id="aclass" class="com.huweiyang.A"></bean>
<bean id="bcalss" class="com.huweiyang.B"></bean>
</beans>
第四步:
完成了上面的操作我们需要来测试功能是否完成,是否有用,所以我们要编写一个测试类来测试我们的代码我可以通过 new classpathxmlapplictionContext(),来读取xml文件
代码如下:
package com.huweiyang;
import org.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
public class Mapping {
public static voidmain(String[] args) {
ApplicationContextobj = new ClassPathXmlApplicationContext("beans.xml");
B sr = (B)obj.getBean("bcalss");
sr.getA();
}
}