1

Is it possible in Spring Boot to autowire object that is marked by @ManagedResource. I'm trying to do that but object is null.

For example:

@Component
@ManagedResource(objectName = MyMBean.MBEAN_NAME)
public class MyMBeanImpl implements MyMBean {
    private String attribute;

    @Override
    @ManagedAttribute(description="some attribute")
    public void setAttribute(String attribute) {
        this.attribute = attribute;
    }
}

Spring creates appropriate MBean. But when I try to autowire this object to use its attribute I'm getting null:

@Component
public final class Consumer {
    @Autowired
    MyMBean mBean;    // is null
    ...
}
piphonom
  • 623
  • 6
  • 14
  • 1
    **Fixed**. Problem was not in `@ManagedResource` at all. Problem was in _field injection_. _Constructor injection_ solved my issue. For more info see [https://stackoverflow.com/questions/39890849/what-exactly-is-field-injection-and-how-to-avoid-it](https://stackoverflow.com/questions/39890849/what-exactly-is-field-injection-and-how-to-avoid-it) – piphonom Sep 01 '17 at 22:01
  • This article can clarify some points: [http://www.baeldung.com/running-setup-logic-on-startup-in-spring](http://www.baeldung.com/running-setup-logic-on-startup-in-spring) – piphonom Nov 05 '17 at 21:31

1 Answers1

1

The @Autowired objects may not get initialized if your configuration is not properly defined. Spring scans for managed components in specified packages. I assume that you have @ComponentScan annotation on your spring boot main class. If your main application class is in a root package, then @ComponentScan annotation can be used without specifying a basePackage attribute. Otherwise you need to specify the base package attribute. You need to specify the basePackage attribute similar to the below:

@ComponentScan("<your_package_to scan_for beans>")

Also the @EnableAutoConfiguration annotation is often placed on your main spring boot application class. This implicitly defines a base package to search for components.

mate00
  • 2,727
  • 5
  • 26
  • 34
Binu George
  • 1,050
  • 10
  • 14
  • 1
    my main app class is in root package and is already marked with `@SpringBootApplication` that includes `@EnableAutoConfiguration` and `@ComponentScan`. All other beans from embedded packages are injected correctly – piphonom Sep 01 '17 at 20:28