spring注解
2016-06-12 21:16
525 查看
一、使用spring注解来构造IOC容器
1)、在applicationContext.xml配置扫描注解包
<context:component-scan base-package="com.test.*"/> 其中base-package指定包名
2)、如果某类上有注解(@Controller/@Service/@Repository/@Component)等,就会将这个对象作为Bean注册到spring容器
二、注解使用注册Bean
1)、@Component是使用spring管理注解的通用形式(表示层、业务层、持久层)
2)、@Controller注册表示层的Bean
@Controller
@RequestMapping("/userAction")
public class UserAction extends BaseAction<User> {
//coding......
}
使用@Controller注解表示Action之后,就表示把UserAction交给Spring容器管理,项目启动后,在Spring容器中会存在一个名字为"userAction"(默认)的action,也可以通过value来设置。@RequestMapping是request请求是的访问路径
3)、@Service注册业务层Bean
@Service("userService")
public class UserServiceImpl implements UserService {
//coding......
}
@Service("userService")注解告诉Spring,当要创建UserServiceImpl实例时,名字必须为"userService",这样当Action要使用UserServiceImp实例时,就由Spring创建好的 UserService注入到Action,示例如下:
//注入userService
@Resource(name="userService")
private UserService userService;
4)、@Repository注册数据持久层Bean
@Repository("userDao")
public class UserDaoImpl extends BaseDao<User> {
//coding......
}
@Repository("userDao")注解告诉Spring,让Spring创建名为"userDao"的UserDaoImpl实例,当Service需要使用Spring创建的名字叫“userDao”的UserDaoImpl 实例时,就可以使用@Resource("userDao")注解告诉Spring,Spring把创建好的userDao注入给Service,示例如下:
@Resource(name="userDao")
private UserDaoImpl userDao;
1)、在applicationContext.xml配置扫描注解包
<context:component-scan base-package="com.test.*"/> 其中base-package指定包名
2)、如果某类上有注解(@Controller/@Service/@Repository/@Component)等,就会将这个对象作为Bean注册到spring容器
二、注解使用注册Bean
1)、@Component是使用spring管理注解的通用形式(表示层、业务层、持久层)
2)、@Controller注册表示层的Bean
@Controller
@RequestMapping("/userAction")
public class UserAction extends BaseAction<User> {
//coding......
}
使用@Controller注解表示Action之后,就表示把UserAction交给Spring容器管理,项目启动后,在Spring容器中会存在一个名字为"userAction"(默认)的action,也可以通过value来设置。@RequestMapping是request请求是的访问路径
3)、@Service注册业务层Bean
@Service("userService")
public class UserServiceImpl implements UserService {
//coding......
}
@Service("userService")注解告诉Spring,当要创建UserServiceImpl实例时,名字必须为"userService",这样当Action要使用UserServiceImp实例时,就由Spring创建好的 UserService注入到Action,示例如下:
//注入userService
@Resource(name="userService")
private UserService userService;
4)、@Repository注册数据持久层Bean
@Repository("userDao")
public class UserDaoImpl extends BaseDao<User> {
//coding......
}
@Repository("userDao")注解告诉Spring,让Spring创建名为"userDao"的UserDaoImpl实例,当Service需要使用Spring创建的名字叫“userDao”的UserDaoImpl 实例时,就可以使用@Resource("userDao")注解告诉Spring,Spring把创建好的userDao注入给Service,示例如下:
@Resource(name="userDao")
private UserDaoImpl userDao;
相关文章推荐
- 如何让进程运行在指定的cpu上
- Java 队列2:循环队列
- 在struts2中默认执行的execute方法
- Java命令——javap
- java排序之快速排序
- 初始static关键字
- 使用jackson解析二维数组
- 《JAVA与模式》之状态模式
- Java里length,length(),size()区别
- Spring 事务
- Java配置环境变量
- 《JAVA与模式》之策略模式
- 深入Java集合:HashMap实现原理
- struts2的action从request获取参数值的两种方式
- [转载]11条Java异常处理的最佳实践
- Struts2 result type(结果类型)
- java反射如何提升性能
- Spring框架及IOC容器
- java基础-mysql
- 面向对象1