Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Autowire a Component which is having constructor with arguments in SpringBoot Application

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??

example code: Class having Autowired Constructor:

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

Class using autowire for component having constructor with arguments:

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

    }

this code fails with message

"Unsatisfied dependency expressed through constructor parameter 0"

while creating bean of type Transformer.

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

like image 436
Radhi Avatar asked May 30 '18 09:05

Radhi


1 Answers

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);
    }
}

Then create a config file

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();
    }
}
like image 185
Dildeep Singh Avatar answered Sep 23 '22 09:09

Dildeep Singh