component-scan
<context:component-scan base-package="com.jd"></context:component-scan>
会扫描该包及其子包下的所有类,如果有@Component(组件)、@Service(服务)、@Controller(控制器)、@Repository(数据仓库)构造型(stereotype)注解所标注的类,则将它们注入到Spring IOC容器中。
相对于直接使用标签来说,使用<context:component-scan base-package="***" />组件扫描大大减少了我们XML的配置量、为我们带来了非常大的便利。
@Autowired
自动装配,使用时需要引包import org.springframework.beans.factory.annotation.Autowired
在app.xml中加入如下两句
<bean id="d" name="d" class="java.util.Date"></bean>
<context:component-scan base-package="com.jd"></context:component-scan>
这是由注解修饰的UserInfoDao类
@Controller
public class UserInfoDao implements IUserInfoDao{
@Autowired
private Date date;
public Date getD() {
return date;
}
}
这是测试类
package com.jd.test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.jd.userinfo.dao.IUserInfoDao;
import com.jd.userinfo.dao.UserInfoDao;
import com.jd.vo.Student;
import com.jd.vo.UserInfo;
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("app.xml");
UserInfoDao userInfoDao = applicationContext.getBean(UserInfoDao.class);
System.out.println(userInfoDao.getD());
}
}
测试的结果为