SpringIOC的应用
导入需要的jar包
配置文件为:
一般不用注解操作时使用<bean id=" " class=" ">来创建对象
<?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-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> <!-- 开启注解 用于激活那些已经在spring容器里注册过的bean(无论是通过xml的方式还是通过package sanning的方式)上面的注解,是一个注解处理工具。--> <context:annotation-config></context:annotation-config> <bean id="userDao" class="cn.bdqn.dao.impl.UserDaoImpl"></bean> <bean id="userService" class="cn.bdqn.service.impl.UserServiceImpl"></bean> </beans>
测试类中可以:
@Test public void testSpring1(){ ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); UserService userService = (UserService)ac.getBean("userService"); User u = new User(); userService.addUser(u); //运行userServiceimpl(在xml中别名为userService)中roleShow()方法 }
如果完全使用注解操作,那么配置文件里就可以这样写
<?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-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> <!-- 加入注解扫描 <context:component-scan>除了具 有<context:annotation-config>的功能之外, <context:component-scan>还可以在指定的package下扫描以及注册javabean 。--> <context:component-scan base-package="cn.bdqn"></context:component-scan> </beans>
测试类中可以:
@Test public void testSpring(){ ApplicationContext ac = new ClassPathXmlApplicationContext("beans-scan.xml"); User user = (User)ac.getBean("user"); user.getRole().roleShow(); //运行roleShow()方法 }
使用注解定义bean:
@Component 用于所有使用注解定义bean
@Component("role") //相当于<bean id="role" class="cn.bdqn.entity.Role"></bean> public class Role {
@Repository 用于标注DAO类
@Repository("userDao") public class UserDaoImpl implements UserDao{
@Service 用于标注Service类
@Service("userService") public class UserServiceImpl implements UserService{
@Controller 用户标注业务类
长路漫漫,键盘作伴~