@Resource和@Component实现零XML配置
1、@Resource的注解:
@Resource是J2EE的注解。意思是说在容器里面找相应的资源。也可以通过name属性指定它name的资源。可以注解到field或者setter上面
public class UserAction {
private UserService userService;
@Resource(name="userService")
public void setUserService(UserService userService) {
this.userService = userService;
}
public void addUser(){
userService.HelloWorld();
}
}
2、@Component
@Component和<context:component-scan base-package="com.spring"></context:component-scan>配合实现无XML配置,只通过注解配置及可将类放入资源容器中。
案例解析:
1、 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: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/> <!-- 配置容器资源扫描的包 --> <context:component-scan base-package="com.spring"></context:component-scan> </beans> 2、 Java文件: 标注资源的注解@Component。括号里面指定的是存入容器的name属性为userService 那么将来我们拿的时候则getBean(“userService”)即可。如果我们不指定userService它默认存入容器bean的key为userServiceImpl这样就可以得到一个装有UserServiceImpl对象的容器
package com.spring.service;
import org.springframework.stereotype.Component;
import com.spring.dao.UserDao;
@Component("userService")
public class UserServiceImpl implements UserService{
private UserDao userDao;
public void init(){
System.out.println("init");
}
public void destory(){
System.out.println("destory");
}
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void HelloWorld(){
System.out.println("helloworld");
}
}
通过@Resource将资源注入进来
因为上文已经配置了容器里面的资源。所以我这里将资源通过@Resource注解将资源注入到相关的属性。请看代码:
@Component("userAction")
public class UserAction {
private UserService userService;
//它会将beans的xml文件配置加入进去
//也可以使用name属性指定byName的指定
@Resource(name="userService")
public void setUserService(UserService userService) {
this.userService = userService;
}
public void addUser(){
userService.HelloWorld();
}
}
测试实现:
通过上文配置的userAction案例来得到这个对象然后调用它里面的方法,因为上文通过了@ Component注解将UserAction的对象配置到了容器里面。所以获得容器之后就可以用这种方法getbean即可
@Test
public void test01(){
BeanFactory applicationContext = new ClassPathXmlApplicationContext("beans.xml");
UserAction user = (UserAction) applicationContext.getBean("userAction");
user.addUser();
}
@Scope和@PostConstruct、@PreDestroy
很简单就相当于前面讲到的作用于和initmethod和destorymethod请看下面代码。不再多说:
@Scope("Singleton")
@Component("userService")
public class UserServiceImpl implements UserService{
private UserDao userDao;
@PostConstruct
public void init(){
System.out.println("init");
}
@PreDestroy
public void destory(){
System.out.println("destory");
}
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void HelloWorld(){
System.out.println("helloworld");
}
}