java Spring带有参数的构造函数注入

时间:2020-06-10 06:36:51

标签: java spring dependency-injection

这是一个示例依赖项类。这只是一个示例,向您展示:

package com.apress.prospring5.ch3;
public class Dependency {
    @Override
    public String toString() { return "Dependency{}"; }
}

在此使用此依赖项。目前,Dependency类正在使用默认构造函数:

package com.apress.prospring5.ch3;

public class ConstructorInjection {

    private Dependency dependency;

    public ConstructorInjection(Dependency dependency) {
        System.out.println("-> Injecting Dependency in ConstructorInjection()");
        this.dependency = dependency;
    }

    @Override
    public String toString() {
    return "ConstructorInjection{" +
           "dependency=" + dependency +
           '}';
    }

}

在此示例中,我正在使用Java Spring 5,因此目前使用基于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:c="http://www.springframework.org/schema/c"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="dependency" class="com.apress.prospring5.ch3.Dependency"/>
    <bean id="consInj" class="com.apress.prospring5.ch3.ConstructorInjection"
          c:dependency-ref="dependency">
    </bean>

</beans>

在这里,我提供了一个将上述代码与public static void main一起使用的示例 主要功能在这里:

package com.apress.prospring5.ch3;

import org.springframework.context.support.GenericXmlApplicationContext;

public class ConInjDemo {

    public static void main(String[] args) {
        GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
        ctx.load("app-context-xml.xml");
        ctx.refresh();

        ConstructorInjection ci = ctx.getBean("consInj", ConstructorInjection.class);
        System.out.println(ci);
    }
}

我的问题是:如果Dependency类是这样的,如何修改代码:

    package com.apress.prospring5.ch3;

    public class Dependency {
        private String name;

        public Dependency(String name) {
            this.name = name;
        }

        @Override
        public String toString() { return "Dependency{"+ this.name +"}"; }
    }

我可能应该使用类似的东西:

 <constructor-arg type="int">
    <value>90</value> 
 </constructor-arg> 

但是不知道如何适应我的示例

0 个答案:

没有答案
相关问题