spring annotation 配置笔记

applicationContext.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"
     [color=green]  xmlns:context="http://www.springframework.org/schema/context"[/color]
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
         [color=green]  http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd"[/color]>
               
    [color=green] <context:annotation-config/>[/color]


  <bean id="u" class="demo.AAA"  init-method="init" destroy-method="destory">
  <!--
    <property name="bbb" ref="bbb"></property>
  -->
  </bean>
  
<bean id="bbb" class="demo.BBB"  init-method="init" destroy-method="destory"></bean>
<bean id="bbb2" class="demo.BBB"  init-method="init" destroy-method="destory"></bean>
</beans>



AAA.java
package demo;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AAA {

	
	/**
	 * @param args
	 */
	
	private BBB bbb;
	
	public void init(){
		System.out.println("AAA...inited..........");
	}
	
	public void destory(){
		System.out.println("AAA...destory.........");
	}
	
	public static void main(String[] args) {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
		        new String[] {"application.xml"});

		// an ApplicationContext is also a BeanFactory (via inheritance)
		BeanFactory factory = context;
		
		
		
		AAA aa=(AAA) factory.getBean("u");
		//BBB bb=(BBB) factory.getBean("bbb");
		//BBB bb1=(BBB) factory.getBean("bbb");
		context.destroy();
		

	}
	
	public void setBbb( BBB bbb) {
		this.bbb = bbb;
	}
	
	@Autowired
/*@Autowired可以写在任一方法前,spring会根据参数类型(byType)在上面的文件中寻找相应的bean进行实例化,如果想要根据名称进行实例化,则需要在参数前加上@Qualifier,如下代码指定名称
*/
	public void dqwdqw(@Qualifier("bbb2")BBB bbb){
		System.out.println("111111111");
	}

	
}




BBB.java

package demo;

public class BBB {
	public BBB(){
		
	}
	public static Integer n=10;
	
	private Integer nnn;

	
	public void init(){
		System.out.println("BBB...inited..........");
	}
	
	public void destory(){
		System.out.println("BBB...destory.........");
	}
	
	public static Integer getN() {
		return n;
	}

	public static void setN(Integer n) {
		BBB.n = n;
	}

	public Integer getNnn() {
		return nnn;
	}

	public void setNnn(Integer nnn) {
		this.nnn = nnn;
	}
	
	
	
}



你可能感兴趣的:(spring)