使用构造函数注入进行 Spring Auto 组件扫描

2024-04-09

我知道如何单独使用自动组件扫描和构造函数注入。http://www.mkyong.com/spring/spring-auto-scanning-components/ http://www.mkyong.com/spring/spring-auto-scanning-components/ http://www.dzone.com/tutorials/java/spring/spring-bean-constructor-injection-1.html http://www.dzone.com/tutorials/java/spring/spring-bean-constructor-injection-1.html

是否可以将自动组件扫描与构造函数注入一起使用?使用自动组件扫描时,spring框架会扫描所有指向的类"base-package"并通过调用不带参数的每个构造函数来创建每个构造函数的实例。让我们说一下如何修改以下类和相关的 spring XML 文件。

package com.fb.common;
@Repository
public class Person {

    private String name;
    private int age;

    public Person(String name, int age){
        this.name=name;
        this.age=age;
    }

    public String toString(){
        return "Name: "+name+" Age:"+age;
    }

}

XML file

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <context:component-scan base-package="com.fb.common" />

    <!--
    <bean id="person" class="com.fb.common.Person">
        <constructor-arg type="java.lang.String" value="DefaultName"/>
        <constructor-arg type="int" value="30"/>
    </bean>
    -->
</beans>

您可以执行以下操作

@Inject // or @Autowired
public Person(@Value("DefaultName") String name, @Value("30") int age){
    this.name=name;
    this.age=age;
}

根据博佐的回答here https://stackoverflow.com/questions/4203302/how-to-inject-a-value-to-bean-constructor-using-annotations, spring 不赞成构造函数注入。也许你不应该这样做。

对于您的问题的评论,应该在

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${org.springframework-version}</version>
</dependency>

For @Inject, 你需要

<dependency>
    <groupId>javax.inject</groupId>
    <artifactId>javax.inject</artifactId>
    <version>1</version>
</dependency>

但你可以使用@Autowired由 Spring 提供。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用构造函数注入进行 Spring Auto 组件扫描 的相关文章

随机推荐