----更加简化的版本
UserAction.java
import javax.annotation.Resource; import org.springframework.stereotype.Component; import org.springframework.stereotype.Controller; //@Component("userAction") // 加入IOC容器 //@Component @Controller // 控制层的组件 public class UserAction { @Resource private UserService userService; public String execute() { userService.save(); return null; } }
UserService.java
import javax.annotation.Resource; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; //@Component("userService") // userService加入ioc容器 //@Component @Service // 表示业务逻辑层的组件 public class UserService { // @Resource // 根据类型查找 【在容器中要确保该类型只有一个变量】 @Resource(name = "userDao") // 根据名称查找 private UserDao userDao; // 去容器中招UserDao类型的变量,找到后就赋值 public void save() { userDao.save(); } }
UserDao.java
import org.springframework.stereotype.Component; import org.springframework.stereotype.Repository; // 把当前对象加入ioc容器 //@Component("userDao") // 相当于bean.xml 【<bean id=userDao class=".." />】 //@Component // 加入ioc容器的UserDao对象的引用名称, 默认与类名一样, 且第一个字母小写 //@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("zengmg:保存用户!!!"); } }
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="zengmg.e_anno2"></context:component-scan> <bean id="userDao" class="zengmg.UserDao" scope="prototype"> </bean> </beans>
测试代码:
import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { // 创建容器对象 private ApplicationContext ac = new ClassPathXmlApplicationContext("zengmg/e_anno2/bean.xml"); @Test public void testExecuteAction() { // 从容器中获取Action UserAction userAction = (UserAction) ac.getBean("userAction"); userAction.execute(); } }
时间: 2024-11-06 07:11:31