应用Spring2.5的@Autowired实现注释型的IOC
使用Spring2.5的@Autowired实现注释型的IOC使用Spring2.5的新特性——Autowired可以实现快速的自动注入,而无
使用Spring2.5的@Autowired实现注释型的IOC
使用Spring2.5的新特性——Autowired可以实现快速的自动注入,而无需在xml文档里面添加bean的声明,大大减少了xml文档的维护。(偶喜欢这个功能,因为偶对xml不感冒)。??????
以下是一个例子:??
先编写接口Man:??
- public?interface?Man?{??? ??
- ??
- ??????public?String?sayHello();??? ??
- ??
- }??? ??
然后写Man的实现类Chinese和American:??
- @Service?? ??
- ??
- public?class?Chinese?implements?Man{??? ??
- ??
- ????public?String?sayHello()?{??? ??
- ??
- ????????return?"I?am?Chinese!";??? ??
- ??
- ????}??? ??
- ??
- }??? ??
- ??
- ?? ??
- ??
- @Service?? ??
- ??
- public?class?American?implements?Man{??? ??
- ??
- ????public?String?sayHello()?{??? ??
- ??
- ????????return?"I?am?American!";??? ??
- ??
- ????}??? ??
- ??
- }??? ??
- ??
????? @Service注释表示定义一个bean,自动根据bean的类名实例化一个首写字母为小写的bean,例如Chinese实例化为chinese,American实例化为american,如果需要自己改名字则:@Service("你自己改的bean名")。??
beans.xml??
- <?xml?version="1.0"?encoding="UTF-8"?>??? ??
- ??
- <beans?xmlns="http://www.springframework.org/schema/beans"?? ??
- ??
- ????????xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"?? ??
- ??
- ????????xmlns:context="http://www.springframework.org/schema/context"?? ??
- ??
- ????????xsi:schemaLocation="http://www.springframework.org/schema/beans???? ??
- ??
- ???????????http://www.springframework.org/schema/beans/spring-beans-2.5.xsd??? ??
- ??
- ???????????http://www.springframework.org/schema/context??? ??
- ??
- ???????????http://www.springframework.org/schema/context/spring-context-2.5.xsd">??? ??
- ??
- ??????<context:annotation-config/>??? ??
- ??
- ??????<context:component-scan?base-package="testspring.main"/>??? ??
- ??
- </beans>??? ??
- ??
在spring的配置文件里面只需要加上<context:annotation-config/>和<context:component-scan base-package="需要实现注入的类所在包"/>,可以使用base-package="*"表示全部的类。??
编写主类测试:??
- @Service?? ??
- ??
- public?class?Main?{??? ??
- ??
- ????@Autowired?? ??
- ??
- ????@Qualifier("chinese")??? ??
- ??
- ????private?Man?man;??? ??
- ??
- ?? ??
- ??
- ????public?static?void?main(String[]?args)?{??? ??
- ??
- ????????//?TODO?code?application?logic?here??????
- 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