Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using class.forname but want to autowire members of the target class

Tags:

java

spring

I have this requirement,

My framework is in a way that it reads the class name from the configuration file as a string and I would like to use methods inside that class.

Obvious solution is to use reflection, I have used reflection and able to call methods I wanted, but the problem is the variables inside the target class are not autowired. I understand I am not letting spring to autowire the fields by using reflection (Spring with class.forname()).

Is there a way for me to autowire the class variables instead of creating new instance? Or Am I in a deadlock situation?

like image 915
Kiran Joshi Avatar asked Nov 26 '25 20:11

Kiran Joshi


1 Answers

Option 1: If you have access to the current Spring ApplicationContext, you could do this as follows:

String className = <load class name from configuration>
Class<?> clazz = Class.forName(className);

ApplicationContext applicationContext = <obtain Spring ApplicationContext>
applicationContext.getBean(clazz);

This of course means that the class whose instance you wish to load is a Spring managed bean. Here is a concrete example:

package org.example.beans;

@Component
class Foo { ... }

@Component
class SpringApplicationContext implements ApplicationContextAware {
  private static ApplicationContext CONTEXT;

  @Override
  public void setApplicationContext(final ApplicationContext context) throws BeansException
    CONTEXT = context;
  }

  public static <T> T getBean(String className) {
    return CONTEXT.getBean(Class.forName(className));
  }
}

Option 2: You could manually create an instance of the required class and then ask Spring to populate its dependencies.

This again requires access to the ApplicationContext. For example:

T object = Class.forName(className).newInstance();

applicationContext..getAutowireCapableBeanFactory().autowireBean(object);
like image 132
manish Avatar answered Nov 29 '25 09:11

manish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!