spring ioc之最基础最简单最明了的annotation注入

本文介绍了如何在Spring中配置注解以实现自动组件扫描,并展示了如何使用@Service等注解来定义服务组件,同时提供了自动注册bean及依赖注入的具体示例。

1、配置applicationContext.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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 注解使用示例 -->
    <!-- 开启注解 -->
    <context:annotation-config />

</beans>


2、自动注册bean注解

<?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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 开启自动检测bean注解 -->
    <!-- base-package表示会扫描com.test.bean及其所有子包,对使用了自动注册注解的类进行自动注册 -->
    <context:component-scan base-package="com.test.bean">
        <!-- 过滤哪些类需要被注册,type有5种类型 -->
        <!-- assignable表示扫描派生与expression指定类型的类 -->
        <!-- annotation表示扫描使用了指定注解标注的类 -->
        <!-- aspectj表示扫描与expression指定的AspectJ表达式匹配的类 -->
        <!-- custom表示使用自定义的TypeFilter实现类 -->
        <!-- regex表示过滤expression指定的正则表达式相匹配的类 -->
        <context:include-filter type="assignable"
            expression="com.test.bean.TestAnnotation" />
        <!-- 过滤哪些类不能被注册 -->
        <context:exclude-filter type="assignable"
            expression="com.test.bean.Ssb" />
    </context:component-scan>

</beans>

 


3、将该类自动注册为bean并将id命名为myService,如果不指定默认为第一个字母小写

/**
 * @Component 标志该类为Spring组件
 * @Controller 标志该类为Spring MVC Controller
 * @Repository 标志该类为数据仓库
 * @Service 标志该类为服务
 */
//
@Service("myService") 

public class MyServiceImpl implements MyService{

    ................
}

 


4、在控制器中注入


//如果是通过@Component注入普通bean,
//那么需要在普通bean中加入默认的构造器,否则将无法实力化bean
public class MyControoler{
    @Resource
    private MyService myService;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值