Jefrey Valencia
Jefrey Valencia

Reputation: 713

How to inject or autowire a Class type with spring?

How Do I wire this class in Spring.

1) Annotation 2) Xml

note: I can already wire other classes just not sure how to wire a class in this scenario

Class<? super Client >

enter code here


public class ClientData2 extends ContainerClass<Client>
{
  public ClientData2(Class<? super Client> type)
        throws IllegalArgumentException
  {
    super(type);
  }
}

Upvotes: 1

Views: 4562

Answers (1)

Bozho
Bozho

Reputation: 597016

If you have a bean of type Class, it's the same as everything else - with @Autowired / @Inject (and optionally @Qualifier)

How to create such a bean? Multiple ways:

  • xml - using factory-method="forName" and constructor-arg passing java.lang.Class
  • using a FactoryBean that produces Class objects
  • java config

However, it is is a bit strange that you need a Class object as bean - you can't inject any dependencies in it. Perhaps you can simply inject the class name (with @Value("${class.name}")) and then use Class.forName(..) in a @PostConstruct method.

Upvotes: 1

Related Questions