Spring中使用annotation注入
来源:互联网 发布:微交易平台代源码 编辑:程序博客网 时间:2024/05/17 04:39
我们使用Spring 一般式在xml配置文件中进行注入.但是这种方式使得配置过于臃肿。试想一个应用中,有上千个对象,而每个对象又需要注入很多其它对象,那么我们的配置文件就显得非常的臃肿了。
Spring2.0 以后,我们可以使用annotation来为Spring的配置文件进行“减肥”
我使用的是Spring2.5.
第一:首先准备需要的jar包:SPRING_FRAMEWORK_HOME为spring发行包所在的目录
A) SPRING_FRAMEWORK_HOME/dist/spring.jar
B) SPRING_FRAMEWORK_HOME/lib/ jakarta-commons/ commons-logging.jar
C) SPRING_FRAMEWORK_HOME/lib/log4j / log4j- 1.2.15.jar(为了在项目中使用log4j输出日志信息)
D) SPRING_FRAMEWORK_HOME/lib/j2ee/common-annotations.jar
第二:引入Spring配置的命名空间以及命名空间的schema文件的配置.这些配置可以到参考手册中找到。参考手册在SPRING_FRAMEWORK_HOME/ docs/reference中。有html版本和pdf版本。找到【3.2.1.1. Configuration metadata】拷贝配置即可
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:annotation-config />
</beans>
在java代码中使用@Autowired或者@Resource注解方式进行装配。但我们要在xml配置中引入以下信息:
A) context命名空间以及这个命名空间的schema文件
B) <context:annotation-config /> 让Spring启用对annotation的支持。它其实是注册了多个对annotation进行解析处理的处理器:
AutowiredAnnotionBeanPostProcessor
CommonAnnotationBeanPostProcessor
PersistenceAnnotionBeanPostProcessor
RequiredAnnotationBeanPostProcessor.
(注意:annotation本身是不能干活的,要想让annotation干活,必须要有处理器来解析annotion)
第三:在java代码中使用@Resource进行注入
public class UserService {
@Resource(name="userDao")
private UserDAO userDao;
public UserDAO getUserDao() {
return userDao;
}
public void setUserDao(UserDAO userDao) {
this.userDao = userDao;
}
public String[] getAllUser(){
return userDao.findUsers();
}
}
第四:配置文件中的配置:
可以看到,我们没有在配置文件中为userService注入userDao,因为在 UserService类中使用annotation的方式注入
http://blog.sina.com.cn/s/blog_4cb8215f0100cyxs.html- Spring中使用annotation注入
- Spring中使用annotation注入
- Spring中使用annotation注入
- Spring中使用annotation注入
- Spring中使用annotation注入
- spring Annotation 组件注入
- 扩展Spring——使用 Annotation将配置资源注入到Bean中
- spring map使用annotation泛型注入问题分析
- spring annotation 注入static 属性
- spring annotation注解 依赖注入
- spring annotation 注入static 属性
- Spring的annotation注入实例
- spring annotation 注入static 属性
- 单元测试中使用spring注入
- Spring中使用Hibernate3的Annotation
- spring 2.5 中配置bean 使用annotation
- Spring中使用Hibernate3的Annotation
- spring中AOP的Annotation使用流程
- JS实现左右键翻页功能
- 配置重复提交的代码后遇到的空指针问题
- 090820c语言日记
- JAVA对话框
- sun 认证
- Spring中使用annotation注入
- win2k,XP下用setupapi.dll自动安装Driver
- 使用Struts的Token机制解决表单的重复提交
- Gaussian安装手册 v1.02
- 热烈庆祝博客新开张!
- .eof() 以及std::getline(ifstream &, string &)
- 邮政储蓄银行厦门分行经营管理系统 项目总结
- 整合时遇到的乱码问题(struts2.1.6SH)
- FileUpLoad控件