简体   繁体   中英

Spring component with constructor argument

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM