注解的使用

纸上得来终觉浅

1.基本注解

@Component  标识了一个受Spring管理的组件

@Respository 标识持久层组件

@Service 标识服务层组件

@Controller 标识表现层组件

@Autowires  将bean注入

@Qualifier 指定注入的bean的名字

受标识的组件遵循Spring命名策略,将类的第一个字母小写,或者手动指定名字。   之后就会创建一个bean,并以名字作为bean名。


2.导入spring-aop的jar包后, 代码示例如下:

@Component
public class Component1{
public void Component1(){
	System.out.println("comonent.comonent1()");
}
}
@Repository("respons")
public class Responsitory1{
	@Autowired
	private Component1 component1;
	public void  Repository1(){
		System.out.println("Responsitory.Repository1()");
		component1.Component1();
	}
}
@Service
public class Service1 {
	@Autowired
	private Responsitory1 x;
	
	@Autowired
	@Qualifier("respons")
	private Responsitory1 x2;
	
	@Autowired(required=false)
	@Qualifier("responsi")
	private Responsitory1 x3;
	
	public void Service1(){
		System.out.println("Service.Service1()");
		x.Repository1();
		x2.Repository1();
//		x3.Repository1();
	}
}

<context:component-scan base-package="com.roadArchitectWeb.Test"></context:component-scan>

public class main {
	public static void main(String[] args) {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
		Service1 service1 = (Service1)ctx.getBean("service1");
		service1.Service1();
	}
}

结果如下:

Service.Service1()
Responsitory.Repository1()
comonent.comonent1()
Responsitory.Repository1()
comonent.comonent1()

上述示例中为什么x是能够被注入到的,因为spring会查找Responsitory类型的bean,既有一个已经注入的“respons”的bean,当需要注入另外一个Responsitory类型的bean时候,不管它的名字是什么,比如x,依然是可以注入的;使用@Qualifier显式的指明当然更好。   但是如果指明一个错误的bean是无法注入的, 要不报错的话需要使用required=false,这时候只要不使用它的相关方法就可以了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值