spring注解1

1. src下目录结构如下:

2.测试类

public class App {

	// 创建容器对象
	private ApplicationContext ac = new ClassPathXmlApplicationContext("cn/itcast/e_anno/bean.xml");

	@Test
	public void testExecuteAction() {
		// 从容器中获取Action
		UserAction userAction = (UserAction) ac.getBean("userAction");
		userAction.execute();
	}
}

 3.控制层

@Controller  // 加入IOC容器
public class UserAction {
	@Autowired
	private UserService userService;

	public String execute() {
		userService.save();
		return null;
	}
}

  4.业务逻辑层

@Service // userService加入ioc容器
public class UserService {
	@Autowired
	private UserDao userDao;

	public void save() {
		userDao.save();
	}
}

  5.持久层

@Repository //  相当于bean.xml 【<bean id=userDao class=".." />】
public class UserDao {
	public void save() {
		System.out.println("DB:保存用户!!!");
	}
}

  6. spring的配置文件

<?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>  

  

 

posted @ 2017-05-07 12:47  黑土白云  阅读(177)  评论(0编辑  收藏  举报