首页 > 代码库 > Spring依赖注入 --- 简单使用说明

Spring依赖注入 --- 简单使用说明

Spring依赖注入 --- 简单使用说明

 

本文将对spring依赖注入的使用做简单的说明,enjoy your time!

 

1.使用Spring提供的依赖注入

对spring依赖注入的实现方法感兴趣的同学可以参考我的日志:http://www.cnblogs.com/kodoyang/p/Frame_Imitate_Spring.html

我们会用spring提供的ClassPathXmlApplicationContext实现来代替这篇日志中相应的实现

为导入的jar文件配置api对应的Library的jar上右键,选择properties>JavadocLocation鼠标停留在对应的类上,按F1就可以看到对应的api文档

ClassPathXmlApplicationContext实现了接口ApplicationContext;接口ApplicationContext继承了BeanFactory的接口
ApplicationContext可以使用的方法更多,所以一般用ApplicationContext

下面是详细的代码:

/Spring_IOC/src/yuki/spring/ioc/pojo/User.java

package yuki.spring.ioc.pojo;public class User {    private String username;    private String password;        public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }    }

/Spring_IOC/src/yuki/spring/ioc/dao/UserDAO.java

package yuki.spring.ioc.dao;import yuki.spring.ioc.pojo.User;public interface UserDAO {        void save(User u);}

/Spring_IOC/src/yuki/spring/ioc/dao/impl/UserDAOImpl.java

package yuki.spring.ioc.dao.impl;import yuki.spring.ioc.dao.UserDAO;import yuki.spring.ioc.pojo.User;public class UserDAOImpl implements UserDAO {    private int daoId;    private String daoStatus;        public int getDaoId() {        return daoId;    }    public void setDaoId(int daoId) {        this.daoId = daoId;    }    public String getDaoStatus() {        return daoStatus;    }    public void setDaoStatus(String daoStatus) {        this.daoStatus = daoStatus;    }    @Override    public void save(User u) {        System.out.println(daoId + ", " + daoStatus);        System.out.println("user saved...");    }}

/Spring_IOC/src/yuki/spring/ioc/service/UserService.java

package yuki.spring.ioc.service;import yuki.spring.ioc.dao.UserDAO;import yuki.spring.ioc.pojo.User;public class UserService {    private UserDAO userDAO;        public UserService(UserDAO userDAO) {        this.userDAO = userDAO;    }        public void add(User u){        this.userDAO.save(u);    }}

/Spring_IOC/src/beans.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"    xsi:schemaLocation="http://www.springframework.org/schema/beans                    http://www.springframework.org/schema/beans/spring-beans.xsd">    <bean id="userDAO" class="yuki.spring.ioc.dao.impl.UserDAOImpl">        <property name="daoId" value="6"></property>        <property name="daoStatus" value="good"></property>    </bean>    <bean id="userService" class="yuki.spring.ioc.service.UserService">        <!-- <property name="userDAO" ref="userDAO"></property> -->        <constructor-arg ref="userDAO"></constructor-arg>    </bean></beans>

/Spring_IOC/test/yuki/spring/ioc/service/UserServiceTest.java

package yuki.spring.ioc.service;import org.junit.Test;//import org.springframework.beans.factory.BeanFactory;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import yuki.spring.ioc.pojo.User;public class UserServiceTest {    @Test    public void testAdd() {        @SuppressWarnings("resource")//      BeanFactory applicationContext = new ClassPathXmlApplicationContext("beans.xml");        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");        UserService userService = (UserService) applicationContext.getBean("userService");        User u = new User();        u.setUsername("username");        u.setPassword("password");        userService.add(u);    }}

运行结果如下:

八月 31, 2014 9:04:55 上午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@3a439b: startup date [Sun Aug 31 09:04:55 CST 2014]; root of context hierarchy八月 31, 2014 9:04:55 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions信息: Loading XML bean definitions from class path resource [beans.xml]6, gooduser saved...

控制反转:把具体的实现反转到了抽象的接口概念上;依赖注入:面向的是接口,注入它的实现

setter注入和构造方法注入,当有多个参数时可以定义索引或类型;可以把简单属性的值放在配置文件中,这很少用

 

2.Bean的生存范围、自动编织

bean的scope属性可以接受的字面值:singleton、prototype、request、session、global session、application
明显是和Web相关的,默认情况下是singleton

在添加XML Catalog Element后,在key后填写文件名

在上下文环境中,取出相同的bean,它们指向同一个对象
在bean上添加属性scope="prototype",prototype的意思是原型,取出来的对象是原型的复制品
如果bean是接收用户请求的action,scope应该设成prototype

/Spring_Scope/src/singleton.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"    xsi:schemaLocation="http://www.springframework.org/schema/beans                         http://www.springframework.org/schema/beans/spring-beans-4.0.xsd ">    <!-- <bean id="userService" class="yuki.spring.ioc.scope.singleton.UserService"></bean> -->    <bean id="userService" class="yuki.spring.ioc.scope.UserService" scope="prototype"></bean></beans>

/Spring_Scope/src/yuki/spring/ioc/scope/UserService.java

package yuki.spring.ioc.scope;public class UserService {}

/Spring_Scope/src/yuki/spring/ioc/scope/ScopeTest.java

package yuki.spring.ioc.scope;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class ScopeTest {    @Test    public void testSingleton() {        @SuppressWarnings("resource")        ApplicationContext context = new ClassPathXmlApplicationContext("singleton.xml");        UserService userService = (UserService) context.getBean("userService");        UserService userService2 = (UserService) context.getBean("userService");        System.out.println(userService == userService2);    }}

运行结果如下:

八月 31, 2014 9:34:53 上午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@265ba4: startup date [Sun Aug 31 09:34:53 CST 2014]; root of context hierarchy八月 31, 2014 9:34:54 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions信息: Loading XML bean definitions from class path resource [singleton.xml]false

集合装配:set、list、map

/Spring_Scope/src/collections.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"    xsi:schemaLocation="http://www.springframework.org/schema/beans                         http://www.springframework.org/schema/beans/spring-beans-4.0.xsd ">    <bean id="userDao" class="yuki.spring.ioc.collections.UserDao">        <property name="sets">            <set>                <value>1</value>                <value>2</value>            </set>        </property>        <property name="lists">            <list>                <value>3</value>                <value>4</value>                <value>5</value>            </list>        </property>        <property name="maps">            <map>                <entry key="6" value="six"></entry>                <entry key="7" value="seven"></entry>                <entry key="8" value="eight"></entry>            </map>        </property>    </bean></beans>

/Spring_Scope/src/yuki/spring/ioc/collections/UserDao.java

package yuki.spring.ioc.collections;import java.util.List;import java.util.Map;import java.util.Set;public class UserDao {    private Set<String> sets;    private List<String> lists;    private Map<String, String> maps;        public Set<String> getSets() {        return sets;    }    public void setSets(Set<String> sets) {        this.sets = sets;    }    public List<String> getLists() {        return lists;    }    public void setLists(List<String> lists) {        this.lists = lists;    }    public Map<String, String> getMaps() {        return maps;    }    public void setMaps(Map<String, String> maps) {        this.maps = maps;    }    }

/Spring_Scope/src/yuki/spring/ioc/collections/CollectionsTest.java

package yuki.spring.ioc.collections;import java.lang.reflect.Method;import java.util.List;import java.util.Map;import java.util.Set;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class CollectionsTest {    @Test    @SuppressWarnings("unchecked")    public void testCollection() throws Exception{        @SuppressWarnings("resource")        ApplicationContext context = new ClassPathXmlApplicationContext("collections.xml");        UserDao userDao = (UserDao) context.getBean("userDao");                Method[] methods = userDao.getClass().getMethods();        for(Method method : methods){            switch(method.getName()){            case "getMaps":                Map<String, String> map =  (Map<String, String>) method.invoke(userDao, new Object[0]);                for(Map.Entry<String, String> entry : map.entrySet())                    System.out.println("map::" + entry.getKey() + " -> " + entry.getValue());                break;            case "getSets":                Set<String> set = (Set<String>) method.invoke(userDao, new Object[0]);                for(String s : set)                    System.out.println("set::" + s);                break;            case "getLists":                List<String> list = (List<String>) method.invoke(userDao, new Object[0]);                for(String s : list)                    System.out.println("list::" + s);                break;            }        }    }}

运行结果如下:

八月 31, 2014 9:36:12 上午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@265ba4: startup date [Sun Aug 31 09:36:12 CST 2014]; root of context hierarchy八月 31, 2014 9:36:12 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions信息: Loading XML bean definitions from class path resource [collections.xml]set::1set::2map::6 -> sixmap::7 -> sevenmap::8 -> eightlist::3list::4list::5

autowire:autodetect、byName、byType、constructor、default、no

/Spring_Scope/src/yuki/spring/ioc/autowire/User.java

 

package yuki.spring.ioc.autowire;public class User {}

 

 

 

/Spring_Scope/src/yuki/spring/ioc/autowire/UserDAO.java

 

package yuki.spring.ioc.autowire;public interface UserDAO {    void save(User user);}

 

 

 

/Spring_Scope/src/yuki/spring/ioc/autowire/UserDAOImpl.java

 

package yuki.spring.ioc.autowire;public class UserDAOImpl implements UserDAO {    private int daoId;    public int getDaoId() {        return daoId;    }    public void setDaoId(int daoId) {        this.daoId = daoId;    }        @Override    public void save(User user) {        System.out.println("user saved... " + daoId);    }}

 

 

 

/Spring_Scope/src/yuki/spring/ioc/autowire/UserService.java

 

package yuki.spring.ioc.autowire;public class UserService {    private UserDAO userDAO;    public void setUserDAO(UserDAO userDAO) {        this.userDAO = userDAO;    }        public void save(User user){        userDAO.save(user);    }}

 

 

 

/Spring_Scope/src/autowire.xml

默认是no,意思是需要手动指定

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://www.springframework.org/schema/beans                         http://www.springframework.org/schema/beans/spring-beans-4.0.xsd ">    <bean id="userDAO" class="yuki.spring.ioc.autowire.UserDAOImpl">        <property name="daoId" value="1"></property>    </bean>    <bean id="userDAO2" class="yuki.spring.ioc.autowire.UserDAOImpl">        <property name="daoId" value="2"></property>    </bean>        <!--     <bean id="userService" class="yuki.spring.ioc.autowire.UserService" autowire="no">        <property name="userDAO" ref="userDAO1"></property>    </bean>     -->    <bean id="userService" class="yuki.spring.ioc.autowire.UserService" autowire="byName"></bean>    </beans>

/Spring_Scope/src/autowire2.xml

default的意思是在beans标签内指定好了的

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://www.springframework.org/schema/beans                         http://www.springframework.org/schema/beans/spring-beans-4.0.xsd "            default-autowire="byType">    <bean id="userDAO" class="yuki.spring.ioc.autowire.UserDAOImpl">        <property name="daoId" value="2"></property>    </bean>    <bean id="userService" class="yuki.spring.ioc.autowire.UserService" autowire="byType"></bean>    </beans>

/Spring_Scope/src/yuki/spring/ioc/autowire/AutowireTest.java

package yuki.spring.ioc.autowire;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class AutowireTest {    @Test    public void testAutowire() throws Exception{        @SuppressWarnings("resource")        ApplicationContext context = new ClassPathXmlApplicationContext("autowire.xml");        UserService service = (UserService) context.getBean("userService");        service.save(new User());    }        @Test    public void testAutowire2() throws Exception{        @SuppressWarnings("resource")        ApplicationContext context = new ClassPathXmlApplicationContext("autowire2.xml");        UserService service = (UserService) context.getBean("userService");        service.save(new User());    }}

运行结果如下:

八月 31, 2014 9:53:12 上午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@265ba4: startup date [Sun Aug 31 09:53:12 CST 2014]; root of context hierarchy八月 31, 2014 9:53:12 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions信息: Loading XML bean definitions from class path resource [autowire.xml]user saved... 1八月 31, 2014 9:53:13 上午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1c0542: startup date [Sun Aug 31 09:53:13 CST 2014]; root of context hierarchy八月 31, 2014 9:53:13 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions信息: Loading XML bean definitions from class path resource [autowire2.xml]user saved... 2

Bean的生命周期
如果不加lazy-init="true",当new出ClassPathXmlApplicationContext时
配置文件里所有的bean就会初始化,beans里有标签属性default-lazy-init
设置为true后,bean在用的时候才会初始化
当应用启动起来非常慢时,可以设置lazy-init
ApplicationContext的接口里没有destroy方法

/Spring_Scope/src/yuki/spring/ioc/lifecycle/UserService.java

package yuki.spring.ioc.lifecycle;public class UserService {    public void init(){        System.out.println("init");    }        public void destroy(){        System.out.println("destroy");    }    }

/Spring_Scope/src/lifecycle.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"    xsi:schemaLocation="http://www.springframework.org/schema/beans                         http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">    <!--             <bean id="userService" class="yuki.spring.ioc.lifecycle.UserService"                 init-method="init" destroy-method="destroy" scope="prototype"></bean>     -->            <bean id="userService" class="yuki.spring.ioc.lifecycle.UserService"                 init-method="init" destroy-method="destroy"></bean>    </beans>

/Spring_Scope/src/yuki/spring/ioc/lifecycle/LifecycleTest.java

package yuki.spring.ioc.lifecycle;import org.springframework.context.support.ClassPathXmlApplicationContext;public class LifecycleTest {    @SuppressWarnings({ "resource", "unused" })    public static void main(String[] args) {        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("lifecycle.xml");        UserService service = (UserService) context.getBean("userService");        UserService service2 = (UserService) context.getBean("userService");        // 这个方法在ApplicationContext的接口里没有        context.destroy();    }}

运行结果如下:

八月 31, 2014 10:07:13 上午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@176fe71: startup date [Sun Aug 31 10:07:13 CST 2014]; root of context hierarchy八月 31, 2014 10:07:14 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions信息: Loading XML bean definitions from class path resource [lifecycle.xml]init八月 31, 2014 10:07:14 上午 org.springframework.context.support.ClassPathXmlApplicationContext doClose信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@176fe71: startup date [Sun Aug 31 10:07:13 CST 2014]; root of context hierarchydestroy

当bean的属性scope="prototype"时,上下文不再监测bean的destroy,所以不要和prototype一起用
作为一个数据源,需要close作为destroy-method方法

目录结构如下:


3.注解:自动编织,合格者

http://www.w3.org/2001/XMLSchema-instanceXML Schema instance namespacedtd文件或xsd文件可以称为元数据文件,xsd文件称为xml文件的schema

<context:annotation-config></context:annotation-config>
它初始化了4个bean:

AutowiredAnnotationBeanPostProcessor,
处理bean初始化后的Autowired注解,默认byType
当有两个相同的要注入的类型时,就会匹配参数名,无法匹配就会报错

在preference>Java>Editor>Content> Assist>AutoActionAuto active triggers for Java 后添加@ 再输入@ 就会自动提示了
qualifier - n.预选赛;(击败对手可进入某竞赛的)合格者;资格赛;外围赛

建议写在setXxx方法上,也可以写在其它的方法上
For a fallback match, the bean name is considered a default qualifier value.
                  为了容错,bean的name默认是qualifier的值

CommonAnnotationBeanPostProcessor,
PersistenceAnnotationBeanPostProcessor,
RequiredAnnotationBeanPostProcessor,
the affected bean property must be populated at configuration time,
                  容错用的,初始化的时候必须注入进来

/Spring_Annotation/src/yuki/spring/annotation/autowired/User.java

 

package yuki.spring.annotation.autowired;public class User {}

 

 

 

/Spring_Annotation/src/yuki/spring/annotation/autowired/UserDAO.java

 

package yuki.spring.annotation.autowired;public interface UserDAO {    void save(User user);}

 

 

 

/Spring_Annotation/src/yuki/spring/annotation/autowired/UserDAOImpl.java

 

package yuki.spring.annotation.autowired;public class UserDAOImpl implements UserDAO {        @Override    public void save(User user) {        System.out.println("user saved... ");    }}

 

 

 

/Spring_Annotation/src/yuki/spring/annotation/autowired/UserService.java

package yuki.spring.annotation.autowired;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;public class UserService {    private UserDAO userDAO;        // 在容器里查找与参数对应类型的bean注入    @Autowired    /*public void setUserDAO(UserDAO userDAO) {        this.userDAO = userDAO;    }*/    public void setUserDAO(@Qualifier("userDAO1") UserDAO userDAO) {        this.userDAO = userDAO;    }        public void save(User user){        userDAO.save(user);    }}

/Spring_Annotation/src/annotation.xml

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:context="http://www.springframework.org/schema/context"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://www.springframework.org/schema/beans                         http://www.springframework.org/schema/beans/spring-beans-4.0.xsd                         http://www.springframework.org/schema/context                         http://www.springframework.org/schema/context/spring-context-4.0.xsd ">        <context:annotation-config></context:annotation-config>        <bean id="userDAO1" class="yuki.spring.annotation.autowired.UserDAOImpl"></bean>    <bean id="userDAO2" class="yuki.spring.annotation.autowired.UserDAOImpl"></bean>        <bean id="userService" class="yuki.spring.annotation.autowired.UserService"></bean></beans>

/Spring_Annotation/src/yuki/spring/annotation/autowired/AutowiredTest.java

package yuki.spring.annotation.autowired;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class AutowiredTest {    @Test    public void testAutowired() throws Exception{        @SuppressWarnings("resource")        ApplicationContext context = new ClassPathXmlApplicationContext("annotation.xml");        UserService service = (UserService) context.getBean("userService");        service.save(new User());    }}

运行结果如下:

八月 31, 2014 10:28:40 上午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@3a439b: startup date [Sun Aug 31 10:28:40 CST 2014]; root of context hierarchy八月 31, 2014 10:28:40 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions信息: Loading XML bean definitions from class path resource [annotation.xml]user saved... 

 

4.注解:资源,组件

JCP(Java Community Process)用来定义java的一些新的标准每一个标准可以成为一个JSR(Java Specification Request)

@Resource表示引用了一个资源,默认是按名称,如果名称找不到,再按类型
填写属性name可以查找对应的bean的id并注入

/Spring_Annotation/src/yuki/spring/annotation/resource/UserDAO.java

 

package yuki.spring.annotation.resource;public interface UserDAO {    void save();}

 

 

 

/Spring_Annotation/src/yuki/spring/annotation/resource/UserDAOImpl.java

 

package yuki.spring.annotation.resource;public class UserDAOImpl implements UserDAO {        @Override    public void save() {        System.out.println("user saved... ");    }}

 

 

 

/Spring_Annotation/src/yuki/spring/annotation/resource/UserService.java

package yuki.spring.annotation.resource;import javax.annotation.Resource;public class UserService {    private UserDAO userDAO;    //  @Resource    @Resource(name="userDAO2")    public void setUserDAO(UserDAO userDAO) {        this.userDAO = userDAO;    }        public void save(){        userDAO.save();    }}

/Spring_Annotation/src/resource.xml

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:context="http://www.springframework.org/schema/context"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://www.springframework.org/schema/beans                         http://www.springframework.org/schema/beans/spring-beans-4.0.xsd                         http://www.springframework.org/schema/context                         http://www.springframework.org/schema/context/spring-context-4.0.xsd ">        <context:annotation-config></context:annotation-config>        <bean id="userDAO" class="yuki.spring.annotation.resource.UserDAOImpl"></bean>    <bean id="userDAO2" class="yuki.spring.annotation.resource.UserDAOImpl"></bean>        <bean id="userService" class="yuki.spring.annotation.resource.UserService"></bean></beans>

/Spring_Annotation/src/yuki/spring/annotation/resource/ResourceTest.java

package yuki.spring.annotation.resource;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class ResourceTest {    @Test    public void testAutowired() throws Exception{        @SuppressWarnings("resource")        ApplicationContext context = new ClassPathXmlApplicationContext("resource.xml");        UserService service = (UserService) context.getBean("userService");        service.save();    }}

运行结果如下:

八月 31, 2014 10:40:33 上午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@3a439b: startup date [Sun Aug 31 10:40:33 CST 2014]; root of context hierarchy八月 31, 2014 10:40:33 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions信息: Loading XML bean definitions from class path resource [resource.xml]user saved... 

<context:component-scan base-package=""></context:component-scan>
在base-backage包下找bean,添加了注解Component的类
默认类名首字母小写作为bean的id,也可以填写value属性,作为bean的名称

/Spring_Annotation/src/yuki/spring/annotation/component/UserDAO.java

package yuki.spring.annotation.component;import org.springframework.stereotype.Component;@Component("u")public class UserDAO {        public void save() {        System.out.println("user saved... ");    }}

/Spring_Annotation/src/yuki/spring/annotation/component/UserService.java

package yuki.spring.annotation.component;import javax.annotation.PostConstruct;import javax.annotation.PreDestroy;import javax.annotation.Resource;import org.springframework.stereotype.Component;@Componentpublic class UserService {    @PostConstruct    public void init(){        System.out.println("init...");    }        private UserDAO userDAO;        @Resource(name="u")    public void setUserDAO(UserDAO userDAO) {        this.userDAO = userDAO;    }        public void save(){        userDAO.save();    }        @PreDestroy    public void destroy(){        System.out.println("destroy...");    }}

/Spring_Annotation/src/component.xml

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:context="http://www.springframework.org/schema/context"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://www.springframework.org/schema/beans                         http://www.springframework.org/schema/beans/spring-beans-4.0.xsd                         http://www.springframework.org/schema/context                         http://www.springframework.org/schema/context/spring-context-4.0.xsd ">        <context:annotation-config></context:annotation-config>    <context:component-scan base-package="yuki.spring.annotation.component"></context:component-scan>    </beans>

/Spring_Annotation/src/yuki/spring/annotation/component/ComponentTest.java

package yuki.spring.annotation.component;import org.junit.Test;import org.springframework.context.support.ClassPathXmlApplicationContext;public class ComponentTest {    @Test    public void testAutowired() throws Exception{        @SuppressWarnings("resource")        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("component.xml");        UserService service = (UserService) context.getBean("userService");        service.save();        context.destroy();    }}

运行结果如下:

八月 31, 2014 10:47:26 上午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@3a439b: startup date [Sun Aug 31 10:47:26 CST 2014]; root of context hierarchy八月 31, 2014 10:47:26 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions信息: Loading XML bean definitions from class path resource [component.xml]init...user saved... 八月 31, 2014 10:47:27 上午 org.springframework.context.support.ClassPathXmlApplicationContext doClose信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@3a439b: startup date [Sun Aug 31 10:47:26 CST 2014]; root of context hierarchydestroy...

 

By default, classes annotated with @Component, @Repository, @Service, @Controller,
or a custom annotation that itself is annotated with @Component  are the only detected candidate components.
                                    默认被这四个注解所注解的类被认为是组件

生存范围: @Scope(BeanDefinition.SCOPE_SINGLETON)放在类的定义之前

PostConstruct和PreDestroy,相当于init和的destroy

目录结构如下:

 

本文参考了[尚学堂马士兵_Spring_IOC]的公开课程

更多好文请关注:http://www.cnblogs.com/kodoyang/

 

kongdongyang

2014/8/31

   

 

Spring依赖注入 --- 简单使用说明