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,<beanid=””class=””> 5,扫描类中被加入@resource注解的属性,然后按照自动装配的方式进行关系建立 6,Autowrie 总结 以上就是本文关于Spring自动装配与扫描注解代码详解的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站: 基于注解的组件扫描详解 spring配置扫描多个包问题解析 如有不足之处,欢迎留言指出。感谢朋友们对本站的支持! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |