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

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

       以下 是一个例子:

       先编写接口 Man

       public interface Man {

           public String sayHello();

}

       然后写 Man 的实现类 ChineseAmerican

       @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 实例化为 chineseAmerican 实例化为 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

        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");

        Main main = (Main) ctx.getBean("main");

        System.out.println(main.getMan().sayHello());

    }

 

    public Man getMan() {

        return man;

    }

}

 

Man 接口前面标上 @Autowired@Qualifier 注释使得 Man 接口可以被容器注入,当 Man 接口存在两个实现类的时候必须指定其中一个来注入,使用实现类首字母小写的字符串来注入。否则可以省略,只写@Autowired

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值