Spring自动装配与扫描注解

1 javabean的自动装配

自动注入,减少xml文件的配置信息。

<?xml version="1.0" encoding="UTF-8"?>
<!-- 到入xml文件的约束 -->
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">
    <!-- 1 实例化Dao对象 id:完成对象的引用 class:指定需要创建的对象对应的类的完全限定名 -->
    <bean id="usersDao" class="org.guangsoft.dao.impl.UsersDaoImpl">
    </bean>
    <!-- 2实例化service autowire:属性的作用,完成对象依赖之间的自动装配 no(默认执行) byName:使用需要注入的属性对应的set的方法名字和spring容器中的对象的id进行匹配,如果能匹配上,进行自动注入 
        byType:使用需要注入的属性对应的set的方法参数类型和spring容器中的对象的类型进行匹配,如果能匹配上,进行自动注入 constructor:在byName和byType之间进行选择(首先byName,如果byName不匹配再byType) 
        实际使用:byName -->
    <bean id="usersService" class="org.guangsoft.service.impl.UsersServiceImpl"
        autowire="byType">
    </bean>
    <!-- 3实例化Action对象 -->
    <bean id="usersAction" class="org.guangsoft.action.UsersAction"
        autowire="byType">
    </bean>
</beans>  

2 spring的扫描注解

使用spring的扫描注解,重构三层结构。配置更少的内容

在applicationContext.xml文件中,导入扫描的xsd

l  开启注解扫描

<?xml version="1.0" encoding="UTF-8"?>
<!-- 到入xml文件的约束 -->
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" [ A1 ]
    xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
     http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context-4.1.xsd
     ">
    <!-- 开启注解扫描 base-package属性:指定需要扫描的包,多个包之间使用,号隔开 a.b.c a.b.d a.b.e -->
    <context:component-scan
        base-package="org.guangsoft.dao.impl,
        org.guangsoft.service.impl,org.guangsoft.action"></context:component-scan>
</beans> 

注解进行总结

类注解:

@controller(给web层的注解)

@service(给serivce层加的注解)

@repository(给dao层加的注解) 

@component(给java类加注解,老版本spring只有这一个注解)

以上三个注解:将对应的类纳入spring容器中对应的

Id:类名第一个字母小写(默认)

如果需要自己指定id需要给三个注解加入String类的参数  

@controller(“uAction”)   id=uAction

@resouce(给需要依赖的对象属性加的注解)

通过自动装配完成需要依赖属性的注入。

参数:name:按照byName进行自动装配

参数:type:按照byType进行自动装配

  

注解执行过程

1,加载spring的容器

2, 扫描spring容器中指定包

3, 扫描指定的包中,加了三个类注解的类,然后将该类纳入spring容器

4, <bean id=””  class=””>

5, 扫描类中被加入@resource注解的属性,然后按照自动装配的方式进行关系建立

6, Autowrie

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值