spring命名空间注入

在spring中,可以通过namespace命名空间注入属性

首先,需要在beans中引入下面两行代码

命名空间属性注入

xmlns:p="http://www.springframework.org/schema/p"

命名空间构造函数注入
xmlns:c="http://www.springframework.org/schema/c"

然后,我们在bean中只需要通过c:_0,c:_....注入构造函数

c:_0,c:_1,c_2,c_3  构造函数的第几个参数

<bean id="dataSource" class="com.namespace.DataSource" 
c:_0
="jdbc:mysql://localhost:3306/empdb"
c:_1
="com.mysql.jdbc.Driver"
c:_2
="root"
c:_3
="root"> </bean>

通过p:属性名-ref或者p:属性名-value注入属性

<bean id="sqlFactory" class="com.namespace.SqlFactory" 
c:_0-ref="dataSource" 
p:dataSource-ref="dataSource" 
p:name="小米">

</bean>

完整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:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
  <!--注入的时候就可以通过c:_0.....注入构造函数-->
  <!--通过p:属性名-ref或者p:属性名-value注入属性-->
   <bean id="dataSource" class="com.namespace.DataSource" 
    c:_0
="jdbc:mysql://localhost:3306/empdb"
    c:_1
="com.mysql.jdbc.Driver"
    c:_2
="root"
    c:_3
="root"> </bean> <bean id="sqlFactory" class="com.namespace.SqlFactory"
  c:_0-ref
="dataSource"
  p:dataSource-ref
="dataSource"
  p:name
="小米"> </bean> </beans>
原文地址:https://www.cnblogs.com/liweixml/p/11788562.html