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

spring 2.5以后可以使用注解的方式添加注入,在xml中这种方式默认是关闭的,需要手动打开,即在xml中添加

@Autowried注解可以用在属性、构造函数、set方法中。在需要注入的类中添加@Autowried注解,在使用的时候,spring会自动加载类实例。

不使用注解xml配置为:


		
	
	
	

注解在属性上的应用

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文件将变得更简洁





	
	
	
	
	


你可能感兴趣的:(java-web,自学之路)