在每个类的上面写上述一些信息,就被spring来管理了
package com.ssm.annotation; import org.springframework.stereotype.Controller; import javax.annotation.Resource; @Controller("userController") //代表是Controller层的bean public class UserController { @Resource(name="userService") //将名字是userService的SpringBean注入到userService变量 private UserService userService; public void save(){ this.userService.save(); System.out.println("UserController.save()"); } }
在resources里面写applicationContext.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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> <!-- <context:annotation-config/> <bean id="userDao" class="com.ssm.annotation.UserDaoImpl"/> <bean id="userService" class="com.ssm.annotation.UserServiceImpl"/> <bean id="userController" class="com.ssm.annotation.UserController"/> --> <!--上面的几行可以替换为:--> <context:component-scan base-package="com.ssm.annotation"/> <!--扫描的包:--> </beans>
Main中使用IOC、DI
package com.ssm.annotation; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Anno { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); UserDao userDao = (UserDao) applicationContext.getBean("userDao"); userDao.save(); UserService userService = (UserService) applicationContext.getBean("userService"); userService.save(); UserController userController = (UserController) applicationContext.getBean("userController"); userController.save(); } }