如何在SpringBoot应用程序中自动装配具有构造函数和参数的组件 [英] How to Autowire a Component which is having constructor with arguments in SpringBoot Application

查看:822
本文介绍了如何在SpringBoot应用程序中自动装配具有构造函数和参数的组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有自动装配构造函数的类.

I have a class having Autowired Constructor.

现在当我在班级中自动装配该班级对象时.如何为构造函数传递参数?

now when i am autowiring this class object in my class. how do i pass arguments for constructor??

示例代码: 具有自动装配构造函数的类:

@Component
public class Transformer {
    private String dataSource;
    @Autowired
    public Transformer(String dataSource)
    {
        this.dataSource = dataSource;
    }
}

使用自动装配的类的具有构造函数并带有参数的组件:

@Component
    public class TransformerUser {
        private String dataSource;
        @Autowired
        public TransformerUser(String dataSource)
        {
            this.dataSource = dataSource;
        }
        @Autowired
        Transformer transformer;

    }

此代码失败,并显示消息

this code fails with message

通过构造函数参数0表示的不满意的依赖关系"

"Unsatisfied dependency expressed through constructor parameter 0"

在创建Transformer类型的bean时.

while creating bean of type Transformer.

我如何在自动装配时将参数传递给Transformer?

how do i pass the arguments to Transformer while Autorwiring it??

推荐答案

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Transformer {
    private String datasource;

    @Autowired
    public Transformer(String datasource) {
        this.datasource=datasource;
        log.info(datasource);
    }
}

然后创建一个配置文件

package com.example.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class BeanConfig {
    @Bean
    public Transformer getTransformerBean() {
        return new Transformer("hello spring");
    }

    @Bean
    public String getStringBean() {
        return new String();
    }
}

这篇关于如何在SpringBoot应用程序中自动装配具有构造函数和参数的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆