随笔录 之 spring 自学杂记(二) -- IOC(二)
3.基于注解的配置
声明bean类或者组件有两种方式:
1、采用 XML 来描述一个 bean 连线
2、注解方式--Spring是能够自动扫描,检测和预定义的项目包并实例化bean
1、首先要在spring.xml中添加:
当
但是要在spring.xml文件中引入context规范约束
xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd ">
2、在bean类或者组件中添加 注解
控制层:
@Controller
public class StudentController {@Autowiredprivate StudentService service ;public void doTestAnnotation(){service.doTestAnnotation();System.out.println("StudentController ......");}
}
服务层:
@Service
public class StudentService {@Autowiredprivate StudentDao dao ;public void doTestAnnotation(){dao.doTestAnnotation();System.out.println("StudentService .......");}}
DAO层:@Repository
public class StudentDao {public void doTestAnnotation(){System.out.println("StudentDao .......");}
}
测试:
@Testpublic void TestAnnotation(){System.out.println("注解方式:");StudentController sc = (StudentController)ac.getBean("studentController");sc.doTestAnnotation();}
结果:
信息: Loading XML bean definitions from class path resource [spring.xml]
注解方式:
StudentDao .......
StudentService .......
StudentController ......
3、常用注解
- @Component – 指示自动扫描组件。
- @Repository – 表示在持久层DAO组件。
- @Service – 表示在业务层服务组件。
- @Controller – 表示在表示层控制器组件。
- @Autowired -表示自动匹配(按照类名)
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
