纸上得来终觉浅
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,这时候只要不使用它的相关方法就可以了。