Spring IOC Java注解描述依赖关系

本文介绍Spring框架如何通过组件扫描自动注册Java类为bean实例,使用@Controller、@Service、@Repository和@Component注解标记不同类型的组件。同时,探讨了@Autowired和@Qualifier注解在依赖注入中的应用。

Spring可以自动搜索Java路径下的Java类,并将其注册成bean实例;
需要使用注解来标记bean类;
@Component:标注一个普通的Spring Bean类
@Controller :标注一个控制器组件
@Service:标注一个业务逻辑组件类
@Repository:标注一个DAO组件类
@Scope:范围
@Scope(“singleton”)为默认 当两个对象一致时,为一个地址
@Scope(“prototype”),即使声明的对象一致,地址也不同
@Autowired :标注自动装配

public interface Axe {
    public void clip();
}

@Component("my")
public class SteelAxe implements Axe {
    public void clip() {
        System.out.println("SteelAxe");
    }
}

@Component
public class People {
    @Autowired
    @Qualifier("my")
    private Axe axe;
    public void go(){
        this.axe.clip();
    }
}


public class Test {
    public static void main(String[] args) {
        ApplicationContext cxt=new ClassPathXmlApplicationContext("bean1.xml");
        People people= cxt.getBean("people",People.class);
        SteelAxe steelAxe= cxt.getBean("my",SteelAxe.class);
        StoneAxe stoneAxe= cxt.getBean("stoneAxe",StoneAxe.class);
        people.go();
    }
}

<?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:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xsi:schemaLocation="
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
       ">
    <context:component-scan base-package="com.helan.c"></context:component-scan>
</beans>
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值