您的位置:首页 > 编程语言 > Java开发

java web之路 spring 基于@Autowried注解的依赖注入

2018-03-02 16:52 281 查看
spring 2.5以后可以使用注解的方式添加注入,在xml中这种方式默认是关闭的,需要手动打开,即在xml中添加
<context:annotation-config />
@Autowried注解可以用在属性、构造函数、set方法中。在需要注入的类中添加@Autowried注解,在使用的时候,spring会自动加载类实例。
不使用注解xml配置为:<bean id="textEditor" class="tutorialspoint.TextEditor" scope="prototype">
<constructor-arg ref="spellChecker"></constructor-arg>
</bean>

<bean id="spellChecker" class="tutorialspoint.SpellChecker" scope="prototype"></bean>注解在属性上的应用package autowired;

import org.springframework.beans.factory.annotation.Autowired;

public class TextEditor {
@Autowired
private SpellChecker spellChecker;

public SpellChecker getSp() {
return spellChecker;
}

public void setSp(SpellChecker spellChecker) {
this.spellChecker = spellChecker;
}

public void spellChecker(){
spellChecker.checkSpelling();
}

}依赖的类package autowired;

public class SpellChecker {
public SpellChecker(){
System.out.println("Inside SpellChecker constructor.");
}

public void checkSpelling(){
System.out.println("Inside checkSpelling." );
}
}main方法package autowired;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
public static void main(String[] arg) {
// TODO Auto-generated constructor stub

ApplicationContext con = new ClassPathXmlApplicationContext("autowired.xml");
TextEditor ted = (TextEditor)con.getBean("textEditor");
ted.spellChecker();
}
}xml文件将变得更简洁<?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-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="textEditor" class="autowired.TextEditor"></bean><!-- 使用注解方式后,不需再写property属性 -->
<bean id="spellChecker" class="autowired.SpellChecker"></bean>

</beans>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: