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_anno2"></context:component-scan>
<bean id="userDao" class="cn.itcast.e_anno2.UserDao" scope="prototype">
</bean>
</beans>
UserDao.java
@Repository // 在持久层可以选择用这个注解
public class UserDao {
public UserDao(){
System.out.println("UserDao.UserDao()");
}
public UserDao(int id){
System.out.println("UserDao.UserDao(int id)" + id);
}
public void save() {
System.out.println("DB:保存用户!!!");
}
}
UserService.java
@Service // 表示业务逻辑层的组件
public class UserService {
// 注意此类中没有setter方法
// @Resource // 根据类型查找 【在容器中要确保该类型只有一个变量】
@Resource(name = "userDao") // 根据名称查找
private UserDao userDao; // 去容器中招UserDao类型的变量,找到后就赋值
public void save() {
userDao.save();
}
}
UserAction.java
package cn.itcast.e_anno2;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
@Controller // 控制层的组件
public class UserAction {
@Resource
private UserService userService;
public String execute() {
userService.save();
return null;
}
}
App.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
// 创建容器对象
private ApplicationContext ac =
new ClassPathXmlApplicationContext("cn/itcast/e_anno2/bean.xml");
@Test
public void testExecuteAction() {
// 从容器中获取Action
UserAction userAction = (UserAction) ac.getBean("userAction");
userAction.execute();
}
}