<?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>
測試類中能夠:java
@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>
測試類中能夠:spring
@Test public void testSpring(){ ApplicationContext ac = new ClassPathXmlApplicationContext("beans-scan.xml"); User user = (User)ac.getBean("user"); user.getRole().roleShow(); //運行roleShow()方法 }
使用註解定義bean:app
@Component("role") //至關於<bean id="role" class="cn.bdqn.entity.Role"></bean> public class Role {
@Repository("userDao") public class UserDaoImpl implements UserDao{
@Service("userService") public class UserServiceImpl implements UserService{