8

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

Radhi
  • 6,289
  • 15
  • 47
  • 68

2 Answers2

7
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();
    }
}
djm.im
  • 3,295
  • 4
  • 30
  • 45
  • Where should one put this config file within the spring **boot** project directory structure? – amy May 13 '21 at 19:53
  • 1
    this configuration file is placed with main spring boot application file or in the package parallel to main file. – Dildeep Singh Jun 04 '21 at 10:16
  • It does not look like it answers the question. Where is the TransformerUser in the answer ... – Olix Dec 23 '21 at 13:18
-1

you can use resource files

1) define a file like database.properties and put a variable like

datasource=example

in this file

2) define a configuration class

@Configuration
@PropertySource(value = {"classpath:resources/database.properties"})
public class PKEServiceFactoryMethod {

   private final Environment environment;

   @Bean
   public String dataSource() {
      return environment.getProperty("dataSource");
   }
}

also you can use placeholder that is much better of using constructor in this case

@Component
@PropertySource(value = {"classpath:resources/database.properties"})
public class Transformer {
    @Value("${dataSource}")
    private String dataSource;
}