-1

I am using jdk8 and need to create a spring-component that will take class-name as constructor argument. However, with my current code I am getting runtime error:

Parameter 0 of constructor in com.some.MyLogger required a bean of type 'java.lang.String' that could not be found

This is my MyLogger class:

@Component
public class MyLogger {

    protected  final Log logger;

    public MyLogger(String  clazz) {
        logger = LogFactory.getLog(clazz);
    }

    public void debug(String format, Object... args)
    {
        if (logger.isDebugEnabled())
        {
            logger.debug(String.format(format, args));
        }
    }

    public void info(String msg)
    {
        logger.debug(msg);
    }
}

And this is how I am trying to create the class:

@SpringBootApplication
public class Application {

    public static void main(String[] args) throws MalformedURLException {
        ApplicationContext context = SpringApplication.run(Application.class, args);
        MyLogger logger = (MyLogger) context.getBean(MyLogger.class, Application.class.getCanonicalName());
        logger.info("================ I AM HERE ====================");
}

May I get any insight on right way of creating this component / What's going wrong here ? Thanks in advance.

VictorGram
  • 2,521
  • 7
  • 48
  • 82
  • Does this post answer your question: https://stackoverflow.com/questions/35108778/spring-bean-with-runtime-constructor-arguments/35114663#35114663 – Ken Bekov Nov 06 '20 at 17:45

1 Answers1

3

Components are by default singleton, so Spring tries to create the singleton instance, but it can't figure out what to specify as the parameter.

Since that component is not intended to be used as a singleton, you need to change the scope to prototype.

@Component
@Scope("prototype")
public class DuoLogger {

See the Spring Framework Documentation, section 1.5. Bean Scopes, for more information about scopes.

Andreas
  • 154,647
  • 11
  • 152
  • 247