1

I have following class:

@Component("persistenceJPAConfig")
public class JPAPersistenceConfig {...}

Using Spring I am able to "inject" the class by adding a method with @Autowired-annotation in my target Class where I want to use JPAPersistenceConfig - Class. I works fine, the class itself is fine.

The Problem is that I have to create a Class at runtime (writing source code and compile it) that has to use the bean as well.

I added the autowired-methods too, but it keeps to be null.

@org.springframework.stereotype.Component("Customers")
public class Customers  {
    public Customers() {
    }
    private org.product.server.database.JPAPersistenceConfig persistenceJPAConfig; 

    @org.springframework.beans.factory.annotation.Autowired 
    public void setPersistenceJPAConfig(org.product.server.database.JPAPersistenceConfig persistenceJPAConfig) {
        this.persistenceJPAConfig = persistenceJPAConfig;
    }  
    public void someMethod() {
        this.persistenceJPAConfig.getClassByName(...)
        // Throws nullpointer
    }
}

Do I have to mark the generated file with @Component too so that it becomes a "managed bean" in Spring? And how is it registered in Spring at runtime?

desperately yours :-)

Randbedingung
  • 247
  • 3
  • 8

2 Answers2

0

You can regiter bean in runtime:

DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) applicationContext.getBeanFactory();
beanFactory.registerBeanDefinition("myClass", BeanDefinitionBuilder.rootBeanDefinition(MyClass.class.getName()).getBeanDefinition());

And if your class have autowired properties, they also will be injected.

vacuum
  • 2,273
  • 3
  • 20
  • 32
0

Besides what @vacuum said you can annotate the generated class with @Component and scan it at runtime to generate the bean with its dependencies using ClassPathScanningCandidateComponentProvider, look here

Community
  • 1
  • 1
Adolfo
  • 798
  • 1
  • 7
  • 15