基于注解开发
除了可以用XML开发之外还可以使用注解
@Component 指定把一个对象加入IOC容器
@Repository 作用同@Component; 在持久层使用(dao)
@Service 作用同@Component; 在业务逻辑层使用(service)
@Controller 作用同@Component; 在控制层使用 (action)
@Resource 属性注入
UserDao.java
package cn.itcast.e_anno;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
// 把当前对象加入ioc容器
//@Component("userDao") // 相当于bean.xml 【<bean id=userDao class=".." />】
@Repository("userDao")
public class UserDao {
public void save() {
System.out.println("DB:保存用户!!!");
}
}
UserService.java
package cn.itcast.e_anno;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
//@Component("userService") // userService加入ioc容器
@Service("userService")
public class UserService {
// 会从IOC容器中找userDao对象,注入到当前字段
/*
* <bean id="" class="">
* <property name="userDao" ref="userDao" /> @Resource相当于这里的配置
* </bean>
*/
@Resource(name = "userDao")
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void save() {
userDao.save();
}
}
UserAction.java
package cn.itcast.e_anno;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
//@Component("userAction") // 加入IOC容器
@Controller("userAction")
public class UserAction {
@Resource(name = "userService")
private UserService userService;
public void setUserService(UserService userService) {
this.userService = userService;
}
public String execute() {
userService.save();
return null;
}
}
bean.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 开启注解扫描 -->
<context:component-scan base-package="cn.itcast.e_anno"></context:component-scan>
</beans>
有的时候 @Resource 也@Resource(”userAction”)是一样的。就是第一个类名的首字母改成小写。