spring ioc 从xml到@autowire二

//UserDAO.java

package spring;

import org.springframework.stereotype.Component;

@Component
public class UserDAO implements UserDAOI {
  public void addUser() {
    System.out.println("addUser");
  }
}

 

//UserManager.java

package spring;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;

@Service
public class UserManager {
    @Autowired
    private UserDAO userDao;

    public void addUser() {
  this.userDao.addUser();
}
    public UserDAO getUserDao() {
  return userDao;
}
    public void setUserDao(UserDAO userDao) {
  this.userDao = userDao;
}

    public static void main(String[] args) {
  ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
  UserManager userManager = appContext.getBean(UserManager.class);
  userManager.addUser();
}
}

 

//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:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd 
http://www.springframework.org/schema/jee 
http://www.springframework.org/schema/jee/spring-jee-3.2.xsd 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/task 
http://www.springframework.org/schema/task/spring-task-3.2.xsd">

    <context:annotation-config />
    <context:component-scan base-package="spring,com.ulewo.ioc">
    </context:component-scan>

</beans>

 

重要 要扫入 的bean 要加上 @Component @Service等注解

 http://blog.csdn.net/zhang6622056/article/details/7697876

//可否不用配置文件 全注解?

posted @ 2017-03-03 14:51  cnchengv  阅读(95)  评论(0)    收藏  举报