spring annotation 配置笔记

本文介绍了一个使用Spring框架的应用程序配置示例,详细展示了如何通过XML配置文件(applicationContext.xml)来定义和管理不同类型的bean。此外,还讨论了依赖注入的基本概念,并通过代码示例解释了如何在实际项目中实现依赖注入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}



}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值