分享

Spring中依赖注入的使用和配置

 IT_易风 2016-03-09

使用方法1:

  //在执行此实例化的时候就会完成所有注入
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");

UserService service = (UserService)ctx.getBean("userService");

 

使用方法2:

复制代码

public class SocketRequest {

/**
* 默认实例
*/
private static final SocketRequest INSTANCE = new SocketRequest();

/**
* 获取默认实例
*
* @return 默认实例
*/
public static SocketRequest get() {
return INSTANCE;
}

/**
* 处理系统控制器操作方法
*
* @param context
* spring上下文
*/
public void methodHolder(ApplicationContext context) {
String[] beans = context.getBeanDefinitionNames();//通过此方法可以获得所有的注入类

}
}

复制代码

 

复制代码
public class GameServer implements ApplicationContextAware{
    @Override
    public void setApplicationContext(ApplicationContext arg0)
            throws BeansException {
        SocketRequest.get().methodHolder(arg0);        
    }
}
复制代码
复制代码
public class mainServer {

    public static void main(String[] args) {

//在执行此实例化的时候就会完成所有注入,同时会调用GameServer的setApplicationContext方法
GameServer server = new ClassPathXmlApplicationContext("server.xml").getBean(GameServer.class);

} 
}
复制代码

 

 Spring配置

1.属性中引用另外的bean

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www./schema/beans"
       xmlns:xsi="http://www./2001/XMLSchema-instance"
       xsi:schemaLocation="http://www./schema/beans
           http://www./schema/beans/spring-beans-2.5.xsd">
    <!-- IoC控制反转 -->
  <bean id="u" class="com.bjsxt.dao.impl.UserDAOImpl">
  </bean>
  <!-- 属性中引用另外的bean-->    
  <bean id="userService" class="com.bjsxt.service.UserService">
      <property name="userDAO" ref="u" />
  </bean>
</beans>
复制代码

 

2.有构造函数的注入

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www./schema/beans"
    xmlns:xsi="http://www./2001/XMLSchema-instance"
    xsi:schemaLocation="http://www./schema/beans
           http://www./schema/beans/spring-beans-2.5.xsd">
    <!-- IoC控制反转 -->
    <bean id="u" class="com.bjsxt.dao.impl.UserDAOImpl">
    </bean>
    <bean id="userService" class="com.bjsxt.service.UserService">
    <!-- 有构造函数的注入 -->
        <constructor-arg>
            <ref bean="u" />
        </constructor-arg>
    </bean>
</beans>
复制代码

 

3.有属性的注入,直接把属性写入,很少用到

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www./schema/beans"
    xmlns:xsi="http://www./2001/XMLSchema-instance"
    xsi:schemaLocation="http://www./schema/beans
           http://www./schema/beans/spring-beans-2.5.xsd">
    <!-- IoC控制反转 -->
    <bean name="u" class="com.bjsxt.dao.impl.UserDAOImpl">
        <!-- 有属性的注入,直接把属性写入,很少用到 -->
        <property name="daoId" value="123"></property>
        <property name="daoStatus" value="DDD"></property>
    </bean>
    <!-- 可以写id也可以写name(如果是name则可以写特殊字符) -->
    <bean id="userService" class="com.bjsxt.service.UserService">
        <constructor-arg>
            <ref bean="u" />
        </constructor-arg>
    </bean>
</beans>
复制代码

 

4.scope范围,默认是singleton即单例,如果是prototype则每次是新实例

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www./schema/beans"
    xmlns:xsi="http://www./2001/XMLSchema-instance"
    xsi:schemaLocation="http://www./schema/beans
           http://www./schema/beans/spring-beans-2.5.xsd">
    <!-- IoC控制反转 -->
    <bean name="u" class="com.bjsxt.dao.impl.UserDAOImpl">
        <property name="daoId" value="123"></property>
        <property name="daoStatus" value="DDD"></property>
    </bean>
    <!-- scope范围,默认是singleton即单例,如果是prototype则每次是新实例 -->
    <bean id="userService" class="com.bjsxt.service.UserService" scope="prototype">
        <constructor-arg>
            <ref bean="u" />
        </constructor-arg>
    </bean>
</beans>
复制代码

 

5.可以注入集合类型

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www./schema/beans"
    xmlns:xsi="http://www./2001/XMLSchema-instance"
    xsi:schemaLocation="http://www./schema/beans
           http://www./schema/beans/spring-beans-2.5.xsd">
    <!-- IoC控制反转 -->
    <bean name="u" class="com.bjsxt.dao.impl.UserDAOImpl">
    <!-- 可以注入集合类型 -->
        <property name="sets">
            <set>
                <value>1</value>
                <value>2</value>
            </set>
        </property>
        <property name="lists">
            <list>
                <value>1</value>
                <value>2</value>
                <value>3</value>
            </list>
        </property>
        <property name="maps">
            <map>
                <entry key="1" value="1"></entry>
                <entry key="2" value="2"></entry>
                <entry key="3" value="3"></entry>
                <entry key="4" value="4"></entry>
            </map>
        </property>
    </bean>
    <bean id="userService" class="com.bjsxt.service.UserService"
        scope="prototype">
        <constructor-arg>
            <ref bean="u" />
        </constructor-arg>
    </bean>
</beans>
复制代码

 

6.自动装配

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www./schema/beans"
    xmlns:xsi="http://www./2001/XMLSchema-instance"
    xsi:schemaLocation="http://www./schema/beans
           http://www./schema/beans/spring-beans-2.5.xsd">
    <!-- IoC控制反转 -->
    <bean name="userDAO" class="com.bjsxt.dao.impl.UserDAOImpl">
        <property name="name" value="myname"></property>
    </bean>
    <!-- 自动装配(用的不多):  
         byName按名称自动匹配(即要装配的bean中的属性名称和配置中的bean名称相同就会自动装配,如UserService类中的属性和userDAO的bean名称相同就自动装配)  
         byType按类型自动匹配 (即要装配的bean中的属性类型和配置中的bean的类型相同就会自动装配,如UserService类中的属性类型和userDAO的bean类型相同就自动装配)
    -->
    <bean id="userService" class="com.bjsxt.service.UserService"
        autowire="default">
    </bean>

</beans>
复制代码

 

7.初始化bean时执行init-method方法和销毁的时候执行destroy-method方法

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www./schema/beans"
    xmlns:xsi="http://www./2001/XMLSchema-instance"
    xsi:schemaLocation="http://www./schema/beans
           http://www./schema/beans/spring-beans-2.5.xsd"
           default-autowire="byName" >
    <!-- IoC控制反转 -->
    <bean name="userDAO" class="com.bjsxt.dao.impl.UserDAOImpl">
        <property name="name" value="myname"></property>
    </bean>
    <!-- 初始化bean时执行init-method方法和销毁的时候执行destroy-method方法 -->
    <bean id="userService" class="com.bjsxt.service.UserService"
        init-method="init" destroy-method="destroy">
    </bean>
</beans>
复制代码

 

8.使用注解

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www./schema/beans"
    xmlns:xsi="http://www./2001/XMLSchema-instance"
    xmlns:context="http://www./schema/context"
    xsi:schemaLocation="http://www./schema/beans
           http://www./schema/beans/spring-beans-2.5.xsd
            http://www./schema/context
           http://www./schema/context/spring-context-2.5.xsd">
    <context:annotation-config></context:annotation-config>
</beans>
复制代码

 

9.扫描包名,包名下的类都可以注入。

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www./schema/beans"
    xmlns:xsi="http://www./2001/XMLSchema-instance"
    xmlns:context="http://www./schema/context"
    xsi:schemaLocation="http://www./schema/beans
           http://www./schema/beans/spring-beans-2.5.xsd
            http://www./schema/context
           http://www./schema/context/spring-context-2.5.xsd">
    <context:component-scan base-package="com.bjsxt"></context:component-scan>
</beans>
复制代码

 

10.实际项目配置参考

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www./2001/XMLSchema-instance" xmlns:jdbc="http://www./schema/jdbc" xmlns="http://www./schema/beans" xmlns:aop="http://www./schema/aop"
    xmlns:tx="http://www./schema/tx" xmlns:context="http://www./schema/context"
    xsi:schemaLocation="http://www./schema/jdbc
                     http://www./schema/jdbc/jdbc.xsd
                     http://www./schema/beans
                     http://www./schema/beans/spring-beans.xsd
                     http://www./schema/tx
                     http://www./schema/tx/spring-tx.xsd
                     http://www./schema/aop
                     http://www./schema/aop/spring-aop.xsd 
                     http://www./schema/context
                     http://www./schema/context/spring-context.xsd">

    <context:property-placeholder location="classpath:system.properties" />

    <context:component-scan base-package="com.egaplay.foi.controller" />
    <context:component-scan base-package="com.egaplay.foi.core.listener" />
    <context:component-scan base-package="com.egaplay.foi.tools.controller" />
    <context:component-scan base-package="com.egaplay.foi.module.*.service" />
    <context:component-scan base-package="com.egaplay.foi.module" resource-pattern="Context.class" />

    <jdbc:repositories base-package="com.egaplay.foi.module.*.dao"></jdbc:repositories>

    <bean class="com.eelpo.framework.socket.server.GameServer">
        <property name="port" value="${port}" />
        <property name="shutdownPort" value="${shutdownPort}" />
        <property name="crossDomainPort" value="${crossDomainPort}" />
        <property name="startCrossDomainServer" value="${startCrossDomainServer}" />
        <property name="shutdownCommand" value="${shutdownCommand}" />
        <property name="executionHandler" ref="executionHandler" />
        <property name="socketIdleStateHandler" ref="socketIdleStateHandler" />
        <property name="gameServerListener" ref="foiServerListener" />
        <property name="socketIdleListener" ref="foiSocketIdleListener" />
        <property name="socketSessionListener" ref="foiSocketSessionListener" />
        <property name="socketContextListener" ref="foiSocketContextListener" />
        <property name="socketRequestListener" ref="foiSocketRequestListener" />
    </bean>

    <bean id="executionHandler" class="org.jboss.netty.handler.execution.ExecutionHandler">
        <constructor-arg index="0">
            <bean class="org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor">
                <constructor-arg index="0" value="${threadPool.corePoolSize}" type="int" />
                <constructor-arg index="1" value="${threadPool.maxChannelMemorySize}" type="long" />
                <constructor-arg index="2" value="${threadPool.maxTotalMemorySize}" type="long" />
                <constructor-arg index="3" value="${threadPool.keepAliveTime}" type="long" />
                <constructor-arg index="4" value="SECONDS" type="java.util.concurrent.TimeUnit" />
                <constructor-arg index="5">
                    <bean class="com.eelpo.framework.utils.concurrent.NamedThreadFactory">
                        <constructor-arg index="0" value="Business Process #" />
                    </bean>
                </constructor-arg>
            </bean>
        </constructor-arg>
    </bean>



    <bean id="socketIdleStateHandler" class="com.eelpo.framework.socket.server.handler.SocketIdleStateHandler">
        <constructor-arg index="0" ref="foiSocketIdleListener" />
        <constructor-arg index="1">
            <bean class="org.jboss.netty.util.HashedWheelTimer">
                <constructor-arg index="0" value="${wheelTimer.tickDuration}" type="long" />
                <constructor-arg index="1" value="SECONDS" type="java.util.concurrent.TimeUnit" />
                <constructor-arg index="2" value="${wheelTimer.ticksPerWheel}" type="int" />
            </bean>
        </constructor-arg>
        <constructor-arg index="2" value="${socketIdle.readerIdleTimeSeconds}" type="int" />
        <constructor-arg index="3" value="${socketIdle.writerIdleTimeSeconds}" type="int" />
        <constructor-arg index="4" value="${socketIdle.allIdleTimeSeconds}" type="int" />
    </bean>



    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="url" value="${jdbc.url}" />
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="connectionProperties" value="${jdbc.connectionProperties}" />
        <property name="defaultAutoCommit" value="${dbcp.defaultAutoCommit}" />
        <property name="defaultCatalog" value="${dbcp.defaultCatalog}" />
        <property name="initialSize" value="${dbcp.initialSize}" />
        <property name="maxActive" value="${dbcp.maxActive}" />
        <property name="maxIdle" value="${dbcp.maxIdle}" />
        <property name="minIdle" value="${dbcp.minIdle}" />
        <property name="maxWait" value="${dbcp.maxWait}" />
        <property name="timeBetweenEvictionRunsMillis" value="${dbcp.timeBetweenEvictionRunsMillis}" />
        <property name="numTestsPerEvictionRun" value="${dbcp.numTestsPerEvictionRun}" />
        <property name="minEvictableIdleTimeMillis" value="${dbcp.minEvictableIdleTimeMillis}" />
        <property name="poolPreparedStatements" value="${dbcp.poolPreparedStatements}" />
        <property name="maxOpenPreparedStatements" value="${dbcp.maxOpenPreparedStatements}" />
        <property name="accessToUnderlyingConnectionAllowed" value="${dbcp.accessToUnderlyingConnectionAllowed}" />
        <property name="removeAbandoned" value="${dbcp.removeAbandoned}" />
        <property name="removeAbandonedTimeout" value="${dbcp.removeAbandonedTimeout}" />
        <property name="logAbandoned" value="${dbcp.logAbandoned}" />
    </bean>
</beans>
复制代码

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多