Spring自动检测组件

要想检测这些类并注册相应的bean,需要在xml中包含以下元素,其中basePackage是两个类的公共父包

 

先看beans.xml的配置(<context:component-scan base-package="com.lbx" />

)

<?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-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:annotation-config />
<context:component-scan base-package="com.lbx" />

</beans>

 

 

要注册的<bean>

package com.lbx.service.impl;


import javax.annotation.Resource;

import org.springframework.stereotype.Component;


import com.lbx.dao.UserDao;
import com.lbx.po.User;
import com.lbx.service.UserService;

@Component("userService")
public class UserServiceImpl implements UserService {
	private UserDao userDao;
	
	public void init(){
		System.out.println("UserServiceImpl.init()");
	}
	
	@Override
	public void add(User user) {
		userDao.add(user);
	}
	
	public UserDao getUserDao() {
		return userDao;
	}
	@Resource//(name="userDao")   //最好用@Resource 不要用@Autowired
	public void setUserDao( UserDao userDao) { 
		this.userDao = userDao;
	}

	public void destroy(){
		System.out.println("UserServiceImpl.destroy()");
	}
	
}

 

你可能感兴趣的:(DAO,spring,xml,bean)