纸上得来终觉浅
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()