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

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;
}


猜你喜欢

转载自xiaoshifanyan.iteye.com/blog/2199218
今日推荐