首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

应用Spring2.5的@Autowired实现注释型的IOC

2012-08-22 
使用Spring2.5的@Autowired实现注释型的IOC使用Spring2.5的新特性——Autowired可以实现快速的自动注入,而无

使用Spring2.5的@Autowired实现注释型的IOC

使用Spring2.5的新特性——Autowired可以实现快速的自动注入,而无需在xml文档里面添加bean的声明,大大减少了xml文档的维护。(偶喜欢这个功能,因为偶对xml不感冒)。??????

以下是一个例子:??

先编写接口Man:??

  1. public?interface?Man?{??? ??
  2. ??
  3. ??????public?String?sayHello();??? ??
  4. ??
  5. }??? ??

然后写Man的实现类Chinese和American:??

  1. @Service?? ??
  2. ??
  3. public?class?Chinese?implements?Man{??? ??
  4. ??
  5. ????public?String?sayHello()?{??? ??
  6. ??
  7. ????????return?"I?am?Chinese!";??? ??
  8. ??
  9. ????}??? ??
  10. ??
  11. }??? ??
  12. ??
  13. ?? ??
  14. ??
  15. @Service?? ??
  16. ??
  17. public?class?American?implements?Man{??? ??
  18. ??
  19. ????public?String?sayHello()?{??? ??
  20. ??
  21. ????????return?"I?am?American!";??? ??
  22. ??
  23. ????}??? ??
  24. ??
  25. }??? ??
  26. ??

????? @Service注释表示定义一个bean,自动根据bean的类名实例化一个首写字母为小写的bean,例如Chinese实例化为chinese,American实例化为american,如果需要自己改名字则:@Service("你自己改的bean名")。??

beans.xml??

  1. <?xml?version="1.0"?encoding="UTF-8"?>??? ??
  2. ??
  3. <beans?xmlns="http://www.springframework.org/schema/beans"?? ??
  4. ??
  5. ????????xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"?? ??
  6. ??
  7. ????????xmlns:context="http://www.springframework.org/schema/context"?? ??
  8. ??
  9. ????????xsi:schemaLocation="http://www.springframework.org/schema/beans???? ??
  10. ??
  11. ???????????http://www.springframework.org/schema/beans/spring-beans-2.5.xsd??? ??
  12. ??
  13. ???????????http://www.springframework.org/schema/context??? ??
  14. ??
  15. ???????????http://www.springframework.org/schema/context/spring-context-2.5.xsd">??? ??
  16. ??
  17. ??????<context:annotation-config/>??? ??
  18. ??
  19. ??????<context:component-scan?base-package="testspring.main"/>??? ??
  20. ??
  21. </beans>??? ??
  22. ??

在spring的配置文件里面只需要加上<context:annotation-config/>和<context:component-scan base-package="需要实现注入的类所在包"/>,可以使用base-package="*"表示全部的类。??

编写主类测试:??

  1. @Service?? ??
  2. ??
  3. public?class?Main?{??? ??
  4. ??
  5. ????@Autowired?? ??
  6. ??
  7. ????@Qualifier("chinese")??? ??
  8. ??
  9. ????private?Man?man;??? ??
  10. ??
  11. ?? ??
  12. ??
  13. ????public?static?void?main(String[]?args)?{??? ??
  14. ??
  15. ????????//?TODO?code?application?logic?here??????
  16. padding-top: 0px !important; padding-right: 3px !important; padding-bottom: 0px !important; padding-left: 10px !important; font-family: Verdana, Georgia, Arial, Helvetica, sans-serif; border-top-style: none; border-right-style: none; border-bottom-style: n

热点排行