Spring injecting or autowiring datasource bean to class

后端 未结 2 1003
栀梦
栀梦 2020-12-06 23:52

this may be a very novice question, but I have searched and either I have a large gap in my understanding or am doing something incorrectly that I cannot figure out.

相关标签:
2条回答
  • 2020-12-07 00:34

    As noted in comments, the problem is that you're manually creating the bean instead of letting Spring container create it. Basically, you're doing this:

    new MyBeanOne()
    

    So Spring container can't inject any of the fields you have configured thus being null e.g. jdbcTemplate field. There are some solutions to this:

    1. Convert your SomeOtherClass into a bean managed by Spring container and let it inject the MyBeanOne instance (probably using @Autowired annotation).

    2. If latter approach can't be done since you need to manually create the bean, you can create the bean manually as shown here: How to create spring beans dynamically?

      But this implementation makes you hardcode somewhere the spring config file name and use it in your code. So, a better approach would be option 3.

    3. Look at this solution: Creating New Spring Beans on Demand, where you create a client abstract class with a method that Spring will implement to retrieve a new instance of your Spring managed bean.


    I found another way to handle this by using @Configurable annotation. By decorating your bean with this annotation, you can create a new instance of the bean on demand and Spring will manage the injection of Spring managed beans for you. But to achieve this, Spring needs to use aspects behind the scenes and you should activate usage of aspects for your project. The explanation is quite long, so I provide links that explain in depth this solution:

    • Spring Framework: 7.8 Using AspectJ with Spring applications
    • Using Spring's @Configurable in three easy steps

    Note that in order to enable this feature, you have to add a java agent when starting the JVM that will weave the class at runtime using aspects.

    0 讨论(0)
  • 2020-12-07 00:46

    NullPointerException on the line: this.jdbcTemplate.update(sql);

    If the NPE is actually on that line, then this.jdbcTemplate is obviously null. If this is true then either:

    • The setDataSource(...) method is not being called in Spring, possibly because the @Autowired is not right somehow. It would be easy to add a System.out.println(...) or put a debugging breakpoint in setDataSource to see if it is being called.

    • If it is being called then maybe there are more than one instance of a.b.c.myBeanOne? Are you for sure getting the instance being called from another class from the Spring context? Put a breakpoint in setDataSource and notice the this object reference id. Then put a breakpoint on the this.jdbcTemplate.update(...) line and make sure that the this reference-id is the same.

    0 讨论(0)
提交回复
热议问题