Why is my Spring @Autowired field null?











up vote
470
down vote

favorite
167












Note: This is intended to be a canonical answer for a common problem.



I have a Spring @Service class (MileageFeeCalculator) that has an @Autowired field (rateService), but the field is null when I try to use it. The logs show that both the MileageFeeCalculator bean and the MileageRateService bean are being created, but I get a NullPointerException whenever I try to call the mileageCharge method on my service bean. Why isn't Spring autowiring the field?



Controller class:



@Controller
public class MileageFeeController {
@RequestMapping("/mileage/{miles}")
@ResponseBody
public float mileageFee(@PathVariable int miles) {
MileageFeeCalculator calc = new MileageFeeCalculator();
return calc.mileageCharge(miles);
}
}


Service class:



@Service
public class MileageFeeCalculator {

@Autowired
private MileageRateService rateService; // <--- should be autowired, is null

public float mileageCharge(final int miles) {
return (miles * rateService.ratePerMile()); // <--- throws NPE
}
}


Service bean that should be autowired in MileageFeeCalculator but it isn't:



@Service
public class MileageRateService {
public float ratePerMile() {
return 0.565f;
}
}


When I try to GET /mileage/3, I get this exception:



java.lang.NullPointerException: null
at com.chrylis.example.spring_autowired_npe.MileageFeeCalculator.mileageCharge(MileageFeeCalculator.java:13)
at com.chrylis.example.spring_autowired_npe.MileageFeeController.mileageFee(MileageFeeController.java:14)
...









share|improve this question




















  • 1




    Another scenario can be when bean F is called inside the constructor of another bean S. In this case pass the required bean F as a parameter to the other beans S constructor and annotate the constructor of S with @Autowire. Remember to annotate the class of the first bean F with @Component.
    – aliopi
    Nov 11 '15 at 12:36












  • I coded up a few examples very similar to this one using Gradle here: github.com/swimorsink/spring-aspectj-examples. Hopefully someone will find it useful.
    – Ross117
    Nov 14 at 2:33















up vote
470
down vote

favorite
167












Note: This is intended to be a canonical answer for a common problem.



I have a Spring @Service class (MileageFeeCalculator) that has an @Autowired field (rateService), but the field is null when I try to use it. The logs show that both the MileageFeeCalculator bean and the MileageRateService bean are being created, but I get a NullPointerException whenever I try to call the mileageCharge method on my service bean. Why isn't Spring autowiring the field?



Controller class:



@Controller
public class MileageFeeController {
@RequestMapping("/mileage/{miles}")
@ResponseBody
public float mileageFee(@PathVariable int miles) {
MileageFeeCalculator calc = new MileageFeeCalculator();
return calc.mileageCharge(miles);
}
}


Service class:



@Service
public class MileageFeeCalculator {

@Autowired
private MileageRateService rateService; // <--- should be autowired, is null

public float mileageCharge(final int miles) {
return (miles * rateService.ratePerMile()); // <--- throws NPE
}
}


Service bean that should be autowired in MileageFeeCalculator but it isn't:



@Service
public class MileageRateService {
public float ratePerMile() {
return 0.565f;
}
}


When I try to GET /mileage/3, I get this exception:



java.lang.NullPointerException: null
at com.chrylis.example.spring_autowired_npe.MileageFeeCalculator.mileageCharge(MileageFeeCalculator.java:13)
at com.chrylis.example.spring_autowired_npe.MileageFeeController.mileageFee(MileageFeeController.java:14)
...









share|improve this question




















  • 1




    Another scenario can be when bean F is called inside the constructor of another bean S. In this case pass the required bean F as a parameter to the other beans S constructor and annotate the constructor of S with @Autowire. Remember to annotate the class of the first bean F with @Component.
    – aliopi
    Nov 11 '15 at 12:36












  • I coded up a few examples very similar to this one using Gradle here: github.com/swimorsink/spring-aspectj-examples. Hopefully someone will find it useful.
    – Ross117
    Nov 14 at 2:33













up vote
470
down vote

favorite
167









up vote
470
down vote

favorite
167






167





Note: This is intended to be a canonical answer for a common problem.



I have a Spring @Service class (MileageFeeCalculator) that has an @Autowired field (rateService), but the field is null when I try to use it. The logs show that both the MileageFeeCalculator bean and the MileageRateService bean are being created, but I get a NullPointerException whenever I try to call the mileageCharge method on my service bean. Why isn't Spring autowiring the field?



Controller class:



@Controller
public class MileageFeeController {
@RequestMapping("/mileage/{miles}")
@ResponseBody
public float mileageFee(@PathVariable int miles) {
MileageFeeCalculator calc = new MileageFeeCalculator();
return calc.mileageCharge(miles);
}
}


Service class:



@Service
public class MileageFeeCalculator {

@Autowired
private MileageRateService rateService; // <--- should be autowired, is null

public float mileageCharge(final int miles) {
return (miles * rateService.ratePerMile()); // <--- throws NPE
}
}


Service bean that should be autowired in MileageFeeCalculator but it isn't:



@Service
public class MileageRateService {
public float ratePerMile() {
return 0.565f;
}
}


When I try to GET /mileage/3, I get this exception:



java.lang.NullPointerException: null
at com.chrylis.example.spring_autowired_npe.MileageFeeCalculator.mileageCharge(MileageFeeCalculator.java:13)
at com.chrylis.example.spring_autowired_npe.MileageFeeController.mileageFee(MileageFeeController.java:14)
...









share|improve this question















Note: This is intended to be a canonical answer for a common problem.



I have a Spring @Service class (MileageFeeCalculator) that has an @Autowired field (rateService), but the field is null when I try to use it. The logs show that both the MileageFeeCalculator bean and the MileageRateService bean are being created, but I get a NullPointerException whenever I try to call the mileageCharge method on my service bean. Why isn't Spring autowiring the field?



Controller class:



@Controller
public class MileageFeeController {
@RequestMapping("/mileage/{miles}")
@ResponseBody
public float mileageFee(@PathVariable int miles) {
MileageFeeCalculator calc = new MileageFeeCalculator();
return calc.mileageCharge(miles);
}
}


Service class:



@Service
public class MileageFeeCalculator {

@Autowired
private MileageRateService rateService; // <--- should be autowired, is null

public float mileageCharge(final int miles) {
return (miles * rateService.ratePerMile()); // <--- throws NPE
}
}


Service bean that should be autowired in MileageFeeCalculator but it isn't:



@Service
public class MileageRateService {
public float ratePerMile() {
return 0.565f;
}
}


When I try to GET /mileage/3, I get this exception:



java.lang.NullPointerException: null
at com.chrylis.example.spring_autowired_npe.MileageFeeCalculator.mileageCharge(MileageFeeCalculator.java:13)
at com.chrylis.example.spring_autowired_npe.MileageFeeController.mileageFee(MileageFeeController.java:14)
...






java spring null nullpointerexception autowired






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 22 '17 at 16:24









Taryn

187k45284348




187k45284348










asked Nov 11 '13 at 0:05









chrylis

49.8k1678114




49.8k1678114








  • 1




    Another scenario can be when bean F is called inside the constructor of another bean S. In this case pass the required bean F as a parameter to the other beans S constructor and annotate the constructor of S with @Autowire. Remember to annotate the class of the first bean F with @Component.
    – aliopi
    Nov 11 '15 at 12:36












  • I coded up a few examples very similar to this one using Gradle here: github.com/swimorsink/spring-aspectj-examples. Hopefully someone will find it useful.
    – Ross117
    Nov 14 at 2:33














  • 1




    Another scenario can be when bean F is called inside the constructor of another bean S. In this case pass the required bean F as a parameter to the other beans S constructor and annotate the constructor of S with @Autowire. Remember to annotate the class of the first bean F with @Component.
    – aliopi
    Nov 11 '15 at 12:36












  • I coded up a few examples very similar to this one using Gradle here: github.com/swimorsink/spring-aspectj-examples. Hopefully someone will find it useful.
    – Ross117
    Nov 14 at 2:33








1




1




Another scenario can be when bean F is called inside the constructor of another bean S. In this case pass the required bean F as a parameter to the other beans S constructor and annotate the constructor of S with @Autowire. Remember to annotate the class of the first bean F with @Component.
– aliopi
Nov 11 '15 at 12:36






Another scenario can be when bean F is called inside the constructor of another bean S. In this case pass the required bean F as a parameter to the other beans S constructor and annotate the constructor of S with @Autowire. Remember to annotate the class of the first bean F with @Component.
– aliopi
Nov 11 '15 at 12:36














I coded up a few examples very similar to this one using Gradle here: github.com/swimorsink/spring-aspectj-examples. Hopefully someone will find it useful.
– Ross117
Nov 14 at 2:33




I coded up a few examples very similar to this one using Gradle here: github.com/swimorsink/spring-aspectj-examples. Hopefully someone will find it useful.
– Ross117
Nov 14 at 2:33












12 Answers
12






active

oldest

votes

















up vote
522
down vote



accepted










The field annotated @Autowired is null because Spring doesn't know about the copy of MileageFeeCalculator that you created with new and didn't know to autowire it.



The Spring Inversion of Control (IoC) container has three main logical components: a registry (called the ApplicationContext) of components (beans) that are available to be used by the application, a configurer system that injects objects' dependencies into them by matching up the dependencies with beans in the context, and a dependency solver that can look at a configuration of many different beans and determine how to instantiate and configure them in the necessary order.



The IoC container isn't magic, and it has no way of knowing about Java objects unless you somehow inform it of them. When you call new, the JVM instantiates a copy of the new object and hands it straight to you--it never goes through the configuration process. There are three ways that you can get your beans configured.



I have posted all of this code, using Spring Boot to launch, at this GitHub project; you can look at a full running project for each approach to see everything you need to make it work. Tag with the NullPointerException: nonworking



Inject your beans



The most preferable option is to let Spring autowire all of your beans; this requires the least amount of code and is the most maintainable. To make the autowiring work like you wanted, also autowire the MileageFeeCalculator like this:



@Controller
public class MileageFeeController {

@Autowired
private MileageFeeCalculator calc;

@RequestMapping("/mileage/{miles}")
@ResponseBody
public float mileageFee(@PathVariable int miles) {
return calc.mileageCharge(miles);
}
}


If you need to create a new instance of your service object for different requests, you can still use injection by using the Spring bean scopes.



Tag that works by injecting the @MileageFeeCalculator service object: working-inject-bean



Use @Configurable



If you really need objects created with new to be autowired, you can use the Spring @Configurable annotation along with AspectJ compile-time weaving to inject your objects. This approach inserts code into your object's constructor that alerts Spring that it's being created so that Spring can configure the new instance. This requires a bit of configuration in your build (such as compiling with ajc) and turning on Spring's runtime configuration handlers (@EnableSpringConfigured with the JavaConfig syntax). This approach is used by the Roo Active Record system to allow new instances of your entities to get the necessary persistence information injected.



@Service
@Configurable
public class MileageFeeCalculator {

@Autowired
private MileageRateService rateService;

public float mileageCharge(final int miles) {
return (miles * rateService.ratePerMile());
}
}


Tag that works by using @Configurable on the service object: working-configurable



Manual bean lookup: not recommended



This approach is suitable only for interfacing with legacy code in special situations. It is nearly always preferable to create a singleton adapter class that Spring can autowire and the legacy code can call, but it is possible to directly ask the Spring application context for a bean.



To do this, you need a class to which Spring can give a reference to the ApplicationContext object:



@Component
public class ApplicationContextHolder implements ApplicationContextAware {
private static ApplicationContext context;

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}

public static ApplicationContext getContext() {
return context;
}
}


Then your legacy code can call getContext() and retrieve the beans it needs:



@Controller
public class MileageFeeController {
@RequestMapping("/mileage/{miles}")
@ResponseBody
public float mileageFee(@PathVariable int miles) {
MileageFeeCalculator calc = ApplicationContextHolder.getContext().getBean(MileageFeeCalculator.class);
return calc.mileageCharge(miles);
}
}


Tag that works by manually looking up the service object in the Spring context: working-manual-lookup






share|improve this answer



















  • 1




    The other thing to look at is making objects for beans in a @Configuration bean, where the method to make an instance of a particular bean class is annotated with @Bean.
    – Donal Fellows
    Nov 11 '13 at 0:12










  • @DonalFellows I'm not entirely sure what you're talking about ("making" is ambiguous). Are you talking about a problem with multiple calls to @Bean methods when using Spring Proxy AOP?
    – chrylis
    Nov 11 '13 at 0:16






  • 1




    Hi there, I am running into a similar issue, however when I use your first suggestion, my application thinks "calc" is null when calling the "mileageFee" method. It's as if it never initializes the @Autowired MileageFeeCalculator calc. Any thoughts?
    – Theo
    Jul 14 '14 at 22:00












  • I think you should add an entry at the top of your answer that explains that retrieving the first bean, the root from which you do everything, should be done through the ApplicationContext. Some users (for which I've closed as duplicates) don't understand this.
    – Sotirios Delimanolis
    Oct 18 '14 at 1:39










  • @SotiriosDelimanolis Please explain the issue; I'm not sure exactly what point you're making.
    – chrylis
    Oct 18 '14 at 2:40


















up vote
46
down vote













If you are not coding a web application, make sure your class in which @Autowiring is done is a spring bean. Typically, spring container won't be aware of the class which we might think of as a spring bean. We have to tell the Spring container about our spring classes.



This can be achieved by configuring in appln-contxt or the better way is to annotate class as @Component and please do not create the annotated class using new operator.
Make sure you get it from Appln-context as below.



@Component
public class MyDemo {


@Autowired
private MyService myService;

/**
* @param args
*/
public static void main(String args) {
// TODO Auto-generated method stub
System.out.println("test");
ApplicationContext ctx=new ClassPathXmlApplicationContext("spring.xml");
System.out.println("ctx>>"+ctx);

Customer c1=null;
MyDemo myDemo=ctx.getBean(MyDemo.class);
System.out.println(myDemo);
myDemo.callService(ctx);


}

public void callService(ApplicationContext ctx) {
// TODO Auto-generated method stub
System.out.println("---callService---");
System.out.println(myService);
myService.callMydao();

}

}





share|improve this answer























  • hi , I gone through your solution, that's correct . And Here I would like to know " Why we don't create instance of annotated class using new operator, may I know the reason behind that.
    – Ashish
    Dec 29 '14 at 11:30






  • 2




    if u create the object using new, u will be handling the life cycle of the bean which contradicts the concept of IOC. We need to ask the container to do it, which does it in a better way
    – Shirish Coolkarni
    Aug 20 '15 at 3:04


















up vote
24
down vote













Actually, you should use either JVM managed Objects or Spring-managed Object to invoke methods.
from your above code in your controller class, you are creating a new object to call your service class which has an auto-wired object.



MileageFeeCalculator calc = new MileageFeeCalculator();


so it won't work that way.



The solution makes this MileageFeeCalculator as an auto-wired object in the Controller itself.



Change your Controller class like below.



@Controller
public class MileageFeeController {

@Autowired
MileageFeeCalculator calc;

@RequestMapping("/mileage/{miles}")
@ResponseBody
public float mileageFee(@PathVariable int miles) {
return calc.mileageCharge(miles);
}
}





share|improve this answer



















  • 1




    This is the answer. Because you're instantiating a new MilageFeeCalculator on your own, Spring isn't involved in the instantiation, so Spring spring has no knowledge the object exists. Thus, it can't do anything to it, like inject dependencies.
    – Robert Greathouse
    Sep 19 '17 at 17:27


















up vote
21
down vote













I once encountered the same issue when I was not quite used to the life in the IoC world. The @Autowired field of one of my beans is null at runtime.



The root cause is, instead of using the auto-created bean maintained by the Spring IoC container (whose @Autowired field is indeed properly injected), I am newing my own instance of that bean type and using it. Of course this one's @Autowired field is null because Spring has no chance to inject it.






share|improve this answer






























    up vote
    17
    down vote













    Your problem is new (object creation in java style)



    MileageFeeCalculator calc = new MileageFeeCalculator();


    With annotation @Service, @Component, @Configuration beans are created in the

    application context of Spring when server is started. But when we create objects
    using new operator the object is not registered in application context which is already created. For Example Employee.java class i have used.



    Check this out:



    public class ConfiguredTenantScopedBeanProcessor implements BeanFactoryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    String name = "tenant";
    System.out.println("Bean factory post processor is initialized");
    beanFactory.registerScope("employee", new Employee());

    Assert.state(beanFactory instanceof BeanDefinitionRegistry,
    "BeanFactory was not a BeanDefinitionRegistry, so CustomScope cannot be used.");
    BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;

    for (String beanName : beanFactory.getBeanDefinitionNames()) {
    BeanDefinition definition = beanFactory.getBeanDefinition(beanName);
    if (name.equals(definition.getScope())) {
    BeanDefinitionHolder proxyHolder = ScopedProxyUtils.createScopedProxy(new BeanDefinitionHolder(definition, beanName), registry, true);
    registry.registerBeanDefinition(beanName, proxyHolder.getBeanDefinition());
    }
    }
    }

    }





    share|improve this answer






























      up vote
      8
      down vote













      It seems to be rare case but here is what happened to me:



      We used @Inject instead of @Autowired which is javaee standard supported by Spring. Every places it worked fine and the beans injected correctly, instead of one place. The bean injection seems the same



      @Inject
      Calculator myCalculator


      At last we found that the error was that we (actually, the Eclipse auto complete feature) imported com.opensymphony.xwork2.Inject instead of javax.inject.Inject !



      So to summarize, make sure that your annotations (@Autowired, @Inject, @Service ,... ) have correct packages!






      share|improve this answer






























        up vote
        7
        down vote













        I'm new to Spring, but I discovered this working solution. Please tell me if it's a deprecable way.



        I make Spring inject applicationContext in this bean:



        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.context.ApplicationContext;
        import org.springframework.stereotype.Component;

        @Component
        public class SpringUtils {

        public static ApplicationContext ctx;

        /**
        * Make Spring inject the application context
        * and save it on a static variable,
        * so that it can be accessed from any point in the application.
        */
        @Autowired
        private void setApplicationContext(ApplicationContext applicationContext) {
        ctx = applicationContext;
        }
        }


        You can put this code also in the main application class if you want.



        Other classes can use it like this:



        MyBean myBean = (MyBean)SpringUtils.ctx.getBean(MyBean.class);


        In this way any bean can be obtained by any object in the application (also intantiated with new) and in a static way.






        share|improve this answer





















        • This pattern is necessary to make Spring beans accessible to legacy code but should be avoided in new code.
          – chrylis
          May 14 '15 at 13:06


















        up vote
        3
        down vote













        I think you have missed to instruct spring to scan classes with annotation.



        You can use @ComponentScan("packageToScan") on the configuration class of your spring application to instruct spring to scan.



        @Service, @Component etc annotations add meta description.



        Spring only injects instances of those classes which are either created as bean or marked with annotation.



        Classes marked with annotation need to be identified by spring before injecting, @ComponentScan instruct spring look for the classes marked with annotation. When Spring finds @Autowired it searches for the related bean, and injects the required instance.



        Adding annotation only, does not fix or facilitate the dependency injection, Spring needs to know where to look for.






        share|improve this answer






























          up vote
          2
          down vote













          Another solution would be putting call:
          SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this)

          To MileageFeeCalculator constructor like this:



          @Service
          public class MileageFeeCalculator {

          @Autowired
          private MileageRateService rateService; // <--- will be autowired when constructor is called

          public MileageFeeCalculator() {
          SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this)
          }

          public float mileageCharge(final int miles) {
          return (miles * rateService.ratePerMile());
          }
          }





          share|improve this answer























          • This uses unsafe publication.
            – chrylis
            Apr 21 '15 at 12:41


















          up vote
          2
          down vote













          You can also fix this issue using @Service annotation on service class and passing the required bean classA as a parameter to the other beans classB constructor and annotate the constructor of classB with @Autowired. Sample snippet here :



          @Service
          public class ClassB {

          private ClassA classA;

          @Autowired
          public ClassB(ClassA classA) {
          this.classA = classA;
          }

          public void useClassAObjectHere(){
          classA.callMethodOnObjectA();
          }
          }





          share|improve this answer























          • this worked for me bu t can you please elaborate on how this is solving the issue ?
            – CruelEngine
            Mar 5 at 12:58






          • 1




            @CruelEngine, look this is constructor injection (where you explicitly setting an object) instead of just using field injection (this is mostly done by spring configuration mostly). So if you are creating a object of ClassB using "new" operator is some other scope then that would not be visible or autowired set for ClassA. Hence, while calling classB.useClassAObjectHere() would throw NPE as classA object was not autowired if you just declare field Injection. Read chrylis is trying to explain same. And this why constructor injection is recommended over field injection. Does it make sense now ?
            – apandey846
            Apr 11 at 8:45










          • now i get it . thanks :)
            – CruelEngine
            Apr 11 at 12:28


















          up vote
          2
          down vote













          UPDATE: Really smart people were quick to point on this answer, which explains the weirdness, described below



          ORIGINAL ANSWER:



          I don't know if it helps anyone, but I was stuck with the same problem even while doing things seemingly right. In my Main method, I have a code like this:



          ApplicationContext context =
          new ClassPathXmlApplicationContext(new String {
          "common.xml",
          "token.xml",
          "pep-config.xml" });
          TokenInitializer ti = context.getBean(TokenInitializer.class);


          and in a token.xml file I've had a line



          <context:component-scan base-package="package.path"/>


          I noticed that the package.path does no longer exist, so I've just dropped the line for good.



          And after that, NPE started coming in. In a pep-config.xml I had just 2 beans:



          <bean id="someAbac" class="com.pep.SomeAbac" init-method="init"/>
          <bean id="settings" class="com.pep.Settings"/>


          and SomeAbac class has a property declared as



          @Autowired private Settings settings;


          for some unknown reason, settings is null in init(), when <context:component-scan/> element is not present at all, but when it's present and has some bs as a basePackage, everything works well. This line now looks like this:



          <context:component-scan base-package="some.shit"/>


          and it works. May be someone can provide an explanation, but for me it's enough right now )






          share|improve this answer



















          • 4




            That answer is the explanation. <context:component-scan/> implicitly enables <context:annotation-config/> necessary for the @Autowired to work.
            – ForNeVeR
            Oct 12 '17 at 4:55




















          up vote
          2
          down vote













          If this is happening in a test class, make sure you haven't forgotten to annotate the class.



          For example, in Spring Boot:



          @RunWith(SpringRunner.class)
          @SpringBootTest
          public class MyTests {
          ....





          share|improve this answer




















            protected by chrylis May 8 '14 at 15:21



            Thank you for your interest in this question.
            Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



            Would you like to answer one of these unanswered questions instead?














            12 Answers
            12






            active

            oldest

            votes








            12 Answers
            12






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            522
            down vote



            accepted










            The field annotated @Autowired is null because Spring doesn't know about the copy of MileageFeeCalculator that you created with new and didn't know to autowire it.



            The Spring Inversion of Control (IoC) container has three main logical components: a registry (called the ApplicationContext) of components (beans) that are available to be used by the application, a configurer system that injects objects' dependencies into them by matching up the dependencies with beans in the context, and a dependency solver that can look at a configuration of many different beans and determine how to instantiate and configure them in the necessary order.



            The IoC container isn't magic, and it has no way of knowing about Java objects unless you somehow inform it of them. When you call new, the JVM instantiates a copy of the new object and hands it straight to you--it never goes through the configuration process. There are three ways that you can get your beans configured.



            I have posted all of this code, using Spring Boot to launch, at this GitHub project; you can look at a full running project for each approach to see everything you need to make it work. Tag with the NullPointerException: nonworking



            Inject your beans



            The most preferable option is to let Spring autowire all of your beans; this requires the least amount of code and is the most maintainable. To make the autowiring work like you wanted, also autowire the MileageFeeCalculator like this:



            @Controller
            public class MileageFeeController {

            @Autowired
            private MileageFeeCalculator calc;

            @RequestMapping("/mileage/{miles}")
            @ResponseBody
            public float mileageFee(@PathVariable int miles) {
            return calc.mileageCharge(miles);
            }
            }


            If you need to create a new instance of your service object for different requests, you can still use injection by using the Spring bean scopes.



            Tag that works by injecting the @MileageFeeCalculator service object: working-inject-bean



            Use @Configurable



            If you really need objects created with new to be autowired, you can use the Spring @Configurable annotation along with AspectJ compile-time weaving to inject your objects. This approach inserts code into your object's constructor that alerts Spring that it's being created so that Spring can configure the new instance. This requires a bit of configuration in your build (such as compiling with ajc) and turning on Spring's runtime configuration handlers (@EnableSpringConfigured with the JavaConfig syntax). This approach is used by the Roo Active Record system to allow new instances of your entities to get the necessary persistence information injected.



            @Service
            @Configurable
            public class MileageFeeCalculator {

            @Autowired
            private MileageRateService rateService;

            public float mileageCharge(final int miles) {
            return (miles * rateService.ratePerMile());
            }
            }


            Tag that works by using @Configurable on the service object: working-configurable



            Manual bean lookup: not recommended



            This approach is suitable only for interfacing with legacy code in special situations. It is nearly always preferable to create a singleton adapter class that Spring can autowire and the legacy code can call, but it is possible to directly ask the Spring application context for a bean.



            To do this, you need a class to which Spring can give a reference to the ApplicationContext object:



            @Component
            public class ApplicationContextHolder implements ApplicationContextAware {
            private static ApplicationContext context;

            @Override
            public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            context = applicationContext;
            }

            public static ApplicationContext getContext() {
            return context;
            }
            }


            Then your legacy code can call getContext() and retrieve the beans it needs:



            @Controller
            public class MileageFeeController {
            @RequestMapping("/mileage/{miles}")
            @ResponseBody
            public float mileageFee(@PathVariable int miles) {
            MileageFeeCalculator calc = ApplicationContextHolder.getContext().getBean(MileageFeeCalculator.class);
            return calc.mileageCharge(miles);
            }
            }


            Tag that works by manually looking up the service object in the Spring context: working-manual-lookup






            share|improve this answer



















            • 1




              The other thing to look at is making objects for beans in a @Configuration bean, where the method to make an instance of a particular bean class is annotated with @Bean.
              – Donal Fellows
              Nov 11 '13 at 0:12










            • @DonalFellows I'm not entirely sure what you're talking about ("making" is ambiguous). Are you talking about a problem with multiple calls to @Bean methods when using Spring Proxy AOP?
              – chrylis
              Nov 11 '13 at 0:16






            • 1




              Hi there, I am running into a similar issue, however when I use your first suggestion, my application thinks "calc" is null when calling the "mileageFee" method. It's as if it never initializes the @Autowired MileageFeeCalculator calc. Any thoughts?
              – Theo
              Jul 14 '14 at 22:00












            • I think you should add an entry at the top of your answer that explains that retrieving the first bean, the root from which you do everything, should be done through the ApplicationContext. Some users (for which I've closed as duplicates) don't understand this.
              – Sotirios Delimanolis
              Oct 18 '14 at 1:39










            • @SotiriosDelimanolis Please explain the issue; I'm not sure exactly what point you're making.
              – chrylis
              Oct 18 '14 at 2:40















            up vote
            522
            down vote



            accepted










            The field annotated @Autowired is null because Spring doesn't know about the copy of MileageFeeCalculator that you created with new and didn't know to autowire it.



            The Spring Inversion of Control (IoC) container has three main logical components: a registry (called the ApplicationContext) of components (beans) that are available to be used by the application, a configurer system that injects objects' dependencies into them by matching up the dependencies with beans in the context, and a dependency solver that can look at a configuration of many different beans and determine how to instantiate and configure them in the necessary order.



            The IoC container isn't magic, and it has no way of knowing about Java objects unless you somehow inform it of them. When you call new, the JVM instantiates a copy of the new object and hands it straight to you--it never goes through the configuration process. There are three ways that you can get your beans configured.



            I have posted all of this code, using Spring Boot to launch, at this GitHub project; you can look at a full running project for each approach to see everything you need to make it work. Tag with the NullPointerException: nonworking



            Inject your beans



            The most preferable option is to let Spring autowire all of your beans; this requires the least amount of code and is the most maintainable. To make the autowiring work like you wanted, also autowire the MileageFeeCalculator like this:



            @Controller
            public class MileageFeeController {

            @Autowired
            private MileageFeeCalculator calc;

            @RequestMapping("/mileage/{miles}")
            @ResponseBody
            public float mileageFee(@PathVariable int miles) {
            return calc.mileageCharge(miles);
            }
            }


            If you need to create a new instance of your service object for different requests, you can still use injection by using the Spring bean scopes.



            Tag that works by injecting the @MileageFeeCalculator service object: working-inject-bean



            Use @Configurable



            If you really need objects created with new to be autowired, you can use the Spring @Configurable annotation along with AspectJ compile-time weaving to inject your objects. This approach inserts code into your object's constructor that alerts Spring that it's being created so that Spring can configure the new instance. This requires a bit of configuration in your build (such as compiling with ajc) and turning on Spring's runtime configuration handlers (@EnableSpringConfigured with the JavaConfig syntax). This approach is used by the Roo Active Record system to allow new instances of your entities to get the necessary persistence information injected.



            @Service
            @Configurable
            public class MileageFeeCalculator {

            @Autowired
            private MileageRateService rateService;

            public float mileageCharge(final int miles) {
            return (miles * rateService.ratePerMile());
            }
            }


            Tag that works by using @Configurable on the service object: working-configurable



            Manual bean lookup: not recommended



            This approach is suitable only for interfacing with legacy code in special situations. It is nearly always preferable to create a singleton adapter class that Spring can autowire and the legacy code can call, but it is possible to directly ask the Spring application context for a bean.



            To do this, you need a class to which Spring can give a reference to the ApplicationContext object:



            @Component
            public class ApplicationContextHolder implements ApplicationContextAware {
            private static ApplicationContext context;

            @Override
            public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            context = applicationContext;
            }

            public static ApplicationContext getContext() {
            return context;
            }
            }


            Then your legacy code can call getContext() and retrieve the beans it needs:



            @Controller
            public class MileageFeeController {
            @RequestMapping("/mileage/{miles}")
            @ResponseBody
            public float mileageFee(@PathVariable int miles) {
            MileageFeeCalculator calc = ApplicationContextHolder.getContext().getBean(MileageFeeCalculator.class);
            return calc.mileageCharge(miles);
            }
            }


            Tag that works by manually looking up the service object in the Spring context: working-manual-lookup






            share|improve this answer



















            • 1




              The other thing to look at is making objects for beans in a @Configuration bean, where the method to make an instance of a particular bean class is annotated with @Bean.
              – Donal Fellows
              Nov 11 '13 at 0:12










            • @DonalFellows I'm not entirely sure what you're talking about ("making" is ambiguous). Are you talking about a problem with multiple calls to @Bean methods when using Spring Proxy AOP?
              – chrylis
              Nov 11 '13 at 0:16






            • 1




              Hi there, I am running into a similar issue, however when I use your first suggestion, my application thinks "calc" is null when calling the "mileageFee" method. It's as if it never initializes the @Autowired MileageFeeCalculator calc. Any thoughts?
              – Theo
              Jul 14 '14 at 22:00












            • I think you should add an entry at the top of your answer that explains that retrieving the first bean, the root from which you do everything, should be done through the ApplicationContext. Some users (for which I've closed as duplicates) don't understand this.
              – Sotirios Delimanolis
              Oct 18 '14 at 1:39










            • @SotiriosDelimanolis Please explain the issue; I'm not sure exactly what point you're making.
              – chrylis
              Oct 18 '14 at 2:40













            up vote
            522
            down vote



            accepted







            up vote
            522
            down vote



            accepted






            The field annotated @Autowired is null because Spring doesn't know about the copy of MileageFeeCalculator that you created with new and didn't know to autowire it.



            The Spring Inversion of Control (IoC) container has three main logical components: a registry (called the ApplicationContext) of components (beans) that are available to be used by the application, a configurer system that injects objects' dependencies into them by matching up the dependencies with beans in the context, and a dependency solver that can look at a configuration of many different beans and determine how to instantiate and configure them in the necessary order.



            The IoC container isn't magic, and it has no way of knowing about Java objects unless you somehow inform it of them. When you call new, the JVM instantiates a copy of the new object and hands it straight to you--it never goes through the configuration process. There are three ways that you can get your beans configured.



            I have posted all of this code, using Spring Boot to launch, at this GitHub project; you can look at a full running project for each approach to see everything you need to make it work. Tag with the NullPointerException: nonworking



            Inject your beans



            The most preferable option is to let Spring autowire all of your beans; this requires the least amount of code and is the most maintainable. To make the autowiring work like you wanted, also autowire the MileageFeeCalculator like this:



            @Controller
            public class MileageFeeController {

            @Autowired
            private MileageFeeCalculator calc;

            @RequestMapping("/mileage/{miles}")
            @ResponseBody
            public float mileageFee(@PathVariable int miles) {
            return calc.mileageCharge(miles);
            }
            }


            If you need to create a new instance of your service object for different requests, you can still use injection by using the Spring bean scopes.



            Tag that works by injecting the @MileageFeeCalculator service object: working-inject-bean



            Use @Configurable



            If you really need objects created with new to be autowired, you can use the Spring @Configurable annotation along with AspectJ compile-time weaving to inject your objects. This approach inserts code into your object's constructor that alerts Spring that it's being created so that Spring can configure the new instance. This requires a bit of configuration in your build (such as compiling with ajc) and turning on Spring's runtime configuration handlers (@EnableSpringConfigured with the JavaConfig syntax). This approach is used by the Roo Active Record system to allow new instances of your entities to get the necessary persistence information injected.



            @Service
            @Configurable
            public class MileageFeeCalculator {

            @Autowired
            private MileageRateService rateService;

            public float mileageCharge(final int miles) {
            return (miles * rateService.ratePerMile());
            }
            }


            Tag that works by using @Configurable on the service object: working-configurable



            Manual bean lookup: not recommended



            This approach is suitable only for interfacing with legacy code in special situations. It is nearly always preferable to create a singleton adapter class that Spring can autowire and the legacy code can call, but it is possible to directly ask the Spring application context for a bean.



            To do this, you need a class to which Spring can give a reference to the ApplicationContext object:



            @Component
            public class ApplicationContextHolder implements ApplicationContextAware {
            private static ApplicationContext context;

            @Override
            public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            context = applicationContext;
            }

            public static ApplicationContext getContext() {
            return context;
            }
            }


            Then your legacy code can call getContext() and retrieve the beans it needs:



            @Controller
            public class MileageFeeController {
            @RequestMapping("/mileage/{miles}")
            @ResponseBody
            public float mileageFee(@PathVariable int miles) {
            MileageFeeCalculator calc = ApplicationContextHolder.getContext().getBean(MileageFeeCalculator.class);
            return calc.mileageCharge(miles);
            }
            }


            Tag that works by manually looking up the service object in the Spring context: working-manual-lookup






            share|improve this answer














            The field annotated @Autowired is null because Spring doesn't know about the copy of MileageFeeCalculator that you created with new and didn't know to autowire it.



            The Spring Inversion of Control (IoC) container has three main logical components: a registry (called the ApplicationContext) of components (beans) that are available to be used by the application, a configurer system that injects objects' dependencies into them by matching up the dependencies with beans in the context, and a dependency solver that can look at a configuration of many different beans and determine how to instantiate and configure them in the necessary order.



            The IoC container isn't magic, and it has no way of knowing about Java objects unless you somehow inform it of them. When you call new, the JVM instantiates a copy of the new object and hands it straight to you--it never goes through the configuration process. There are three ways that you can get your beans configured.



            I have posted all of this code, using Spring Boot to launch, at this GitHub project; you can look at a full running project for each approach to see everything you need to make it work. Tag with the NullPointerException: nonworking



            Inject your beans



            The most preferable option is to let Spring autowire all of your beans; this requires the least amount of code and is the most maintainable. To make the autowiring work like you wanted, also autowire the MileageFeeCalculator like this:



            @Controller
            public class MileageFeeController {

            @Autowired
            private MileageFeeCalculator calc;

            @RequestMapping("/mileage/{miles}")
            @ResponseBody
            public float mileageFee(@PathVariable int miles) {
            return calc.mileageCharge(miles);
            }
            }


            If you need to create a new instance of your service object for different requests, you can still use injection by using the Spring bean scopes.



            Tag that works by injecting the @MileageFeeCalculator service object: working-inject-bean



            Use @Configurable



            If you really need objects created with new to be autowired, you can use the Spring @Configurable annotation along with AspectJ compile-time weaving to inject your objects. This approach inserts code into your object's constructor that alerts Spring that it's being created so that Spring can configure the new instance. This requires a bit of configuration in your build (such as compiling with ajc) and turning on Spring's runtime configuration handlers (@EnableSpringConfigured with the JavaConfig syntax). This approach is used by the Roo Active Record system to allow new instances of your entities to get the necessary persistence information injected.



            @Service
            @Configurable
            public class MileageFeeCalculator {

            @Autowired
            private MileageRateService rateService;

            public float mileageCharge(final int miles) {
            return (miles * rateService.ratePerMile());
            }
            }


            Tag that works by using @Configurable on the service object: working-configurable



            Manual bean lookup: not recommended



            This approach is suitable only for interfacing with legacy code in special situations. It is nearly always preferable to create a singleton adapter class that Spring can autowire and the legacy code can call, but it is possible to directly ask the Spring application context for a bean.



            To do this, you need a class to which Spring can give a reference to the ApplicationContext object:



            @Component
            public class ApplicationContextHolder implements ApplicationContextAware {
            private static ApplicationContext context;

            @Override
            public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            context = applicationContext;
            }

            public static ApplicationContext getContext() {
            return context;
            }
            }


            Then your legacy code can call getContext() and retrieve the beans it needs:



            @Controller
            public class MileageFeeController {
            @RequestMapping("/mileage/{miles}")
            @ResponseBody
            public float mileageFee(@PathVariable int miles) {
            MileageFeeCalculator calc = ApplicationContextHolder.getContext().getBean(MileageFeeCalculator.class);
            return calc.mileageCharge(miles);
            }
            }


            Tag that works by manually looking up the service object in the Spring context: working-manual-lookup







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Feb 28 '16 at 19:40

























            answered Nov 11 '13 at 0:05









            chrylis

            49.8k1678114




            49.8k1678114








            • 1




              The other thing to look at is making objects for beans in a @Configuration bean, where the method to make an instance of a particular bean class is annotated with @Bean.
              – Donal Fellows
              Nov 11 '13 at 0:12










            • @DonalFellows I'm not entirely sure what you're talking about ("making" is ambiguous). Are you talking about a problem with multiple calls to @Bean methods when using Spring Proxy AOP?
              – chrylis
              Nov 11 '13 at 0:16






            • 1




              Hi there, I am running into a similar issue, however when I use your first suggestion, my application thinks "calc" is null when calling the "mileageFee" method. It's as if it never initializes the @Autowired MileageFeeCalculator calc. Any thoughts?
              – Theo
              Jul 14 '14 at 22:00












            • I think you should add an entry at the top of your answer that explains that retrieving the first bean, the root from which you do everything, should be done through the ApplicationContext. Some users (for which I've closed as duplicates) don't understand this.
              – Sotirios Delimanolis
              Oct 18 '14 at 1:39










            • @SotiriosDelimanolis Please explain the issue; I'm not sure exactly what point you're making.
              – chrylis
              Oct 18 '14 at 2:40














            • 1




              The other thing to look at is making objects for beans in a @Configuration bean, where the method to make an instance of a particular bean class is annotated with @Bean.
              – Donal Fellows
              Nov 11 '13 at 0:12










            • @DonalFellows I'm not entirely sure what you're talking about ("making" is ambiguous). Are you talking about a problem with multiple calls to @Bean methods when using Spring Proxy AOP?
              – chrylis
              Nov 11 '13 at 0:16






            • 1




              Hi there, I am running into a similar issue, however when I use your first suggestion, my application thinks "calc" is null when calling the "mileageFee" method. It's as if it never initializes the @Autowired MileageFeeCalculator calc. Any thoughts?
              – Theo
              Jul 14 '14 at 22:00












            • I think you should add an entry at the top of your answer that explains that retrieving the first bean, the root from which you do everything, should be done through the ApplicationContext. Some users (for which I've closed as duplicates) don't understand this.
              – Sotirios Delimanolis
              Oct 18 '14 at 1:39










            • @SotiriosDelimanolis Please explain the issue; I'm not sure exactly what point you're making.
              – chrylis
              Oct 18 '14 at 2:40








            1




            1




            The other thing to look at is making objects for beans in a @Configuration bean, where the method to make an instance of a particular bean class is annotated with @Bean.
            – Donal Fellows
            Nov 11 '13 at 0:12




            The other thing to look at is making objects for beans in a @Configuration bean, where the method to make an instance of a particular bean class is annotated with @Bean.
            – Donal Fellows
            Nov 11 '13 at 0:12












            @DonalFellows I'm not entirely sure what you're talking about ("making" is ambiguous). Are you talking about a problem with multiple calls to @Bean methods when using Spring Proxy AOP?
            – chrylis
            Nov 11 '13 at 0:16




            @DonalFellows I'm not entirely sure what you're talking about ("making" is ambiguous). Are you talking about a problem with multiple calls to @Bean methods when using Spring Proxy AOP?
            – chrylis
            Nov 11 '13 at 0:16




            1




            1




            Hi there, I am running into a similar issue, however when I use your first suggestion, my application thinks "calc" is null when calling the "mileageFee" method. It's as if it never initializes the @Autowired MileageFeeCalculator calc. Any thoughts?
            – Theo
            Jul 14 '14 at 22:00






            Hi there, I am running into a similar issue, however when I use your first suggestion, my application thinks "calc" is null when calling the "mileageFee" method. It's as if it never initializes the @Autowired MileageFeeCalculator calc. Any thoughts?
            – Theo
            Jul 14 '14 at 22:00














            I think you should add an entry at the top of your answer that explains that retrieving the first bean, the root from which you do everything, should be done through the ApplicationContext. Some users (for which I've closed as duplicates) don't understand this.
            – Sotirios Delimanolis
            Oct 18 '14 at 1:39




            I think you should add an entry at the top of your answer that explains that retrieving the first bean, the root from which you do everything, should be done through the ApplicationContext. Some users (for which I've closed as duplicates) don't understand this.
            – Sotirios Delimanolis
            Oct 18 '14 at 1:39












            @SotiriosDelimanolis Please explain the issue; I'm not sure exactly what point you're making.
            – chrylis
            Oct 18 '14 at 2:40




            @SotiriosDelimanolis Please explain the issue; I'm not sure exactly what point you're making.
            – chrylis
            Oct 18 '14 at 2:40












            up vote
            46
            down vote













            If you are not coding a web application, make sure your class in which @Autowiring is done is a spring bean. Typically, spring container won't be aware of the class which we might think of as a spring bean. We have to tell the Spring container about our spring classes.



            This can be achieved by configuring in appln-contxt or the better way is to annotate class as @Component and please do not create the annotated class using new operator.
            Make sure you get it from Appln-context as below.



            @Component
            public class MyDemo {


            @Autowired
            private MyService myService;

            /**
            * @param args
            */
            public static void main(String args) {
            // TODO Auto-generated method stub
            System.out.println("test");
            ApplicationContext ctx=new ClassPathXmlApplicationContext("spring.xml");
            System.out.println("ctx>>"+ctx);

            Customer c1=null;
            MyDemo myDemo=ctx.getBean(MyDemo.class);
            System.out.println(myDemo);
            myDemo.callService(ctx);


            }

            public void callService(ApplicationContext ctx) {
            // TODO Auto-generated method stub
            System.out.println("---callService---");
            System.out.println(myService);
            myService.callMydao();

            }

            }





            share|improve this answer























            • hi , I gone through your solution, that's correct . And Here I would like to know " Why we don't create instance of annotated class using new operator, may I know the reason behind that.
              – Ashish
              Dec 29 '14 at 11:30






            • 2




              if u create the object using new, u will be handling the life cycle of the bean which contradicts the concept of IOC. We need to ask the container to do it, which does it in a better way
              – Shirish Coolkarni
              Aug 20 '15 at 3:04















            up vote
            46
            down vote













            If you are not coding a web application, make sure your class in which @Autowiring is done is a spring bean. Typically, spring container won't be aware of the class which we might think of as a spring bean. We have to tell the Spring container about our spring classes.



            This can be achieved by configuring in appln-contxt or the better way is to annotate class as @Component and please do not create the annotated class using new operator.
            Make sure you get it from Appln-context as below.



            @Component
            public class MyDemo {


            @Autowired
            private MyService myService;

            /**
            * @param args
            */
            public static void main(String args) {
            // TODO Auto-generated method stub
            System.out.println("test");
            ApplicationContext ctx=new ClassPathXmlApplicationContext("spring.xml");
            System.out.println("ctx>>"+ctx);

            Customer c1=null;
            MyDemo myDemo=ctx.getBean(MyDemo.class);
            System.out.println(myDemo);
            myDemo.callService(ctx);


            }

            public void callService(ApplicationContext ctx) {
            // TODO Auto-generated method stub
            System.out.println("---callService---");
            System.out.println(myService);
            myService.callMydao();

            }

            }





            share|improve this answer























            • hi , I gone through your solution, that's correct . And Here I would like to know " Why we don't create instance of annotated class using new operator, may I know the reason behind that.
              – Ashish
              Dec 29 '14 at 11:30






            • 2




              if u create the object using new, u will be handling the life cycle of the bean which contradicts the concept of IOC. We need to ask the container to do it, which does it in a better way
              – Shirish Coolkarni
              Aug 20 '15 at 3:04













            up vote
            46
            down vote










            up vote
            46
            down vote









            If you are not coding a web application, make sure your class in which @Autowiring is done is a spring bean. Typically, spring container won't be aware of the class which we might think of as a spring bean. We have to tell the Spring container about our spring classes.



            This can be achieved by configuring in appln-contxt or the better way is to annotate class as @Component and please do not create the annotated class using new operator.
            Make sure you get it from Appln-context as below.



            @Component
            public class MyDemo {


            @Autowired
            private MyService myService;

            /**
            * @param args
            */
            public static void main(String args) {
            // TODO Auto-generated method stub
            System.out.println("test");
            ApplicationContext ctx=new ClassPathXmlApplicationContext("spring.xml");
            System.out.println("ctx>>"+ctx);

            Customer c1=null;
            MyDemo myDemo=ctx.getBean(MyDemo.class);
            System.out.println(myDemo);
            myDemo.callService(ctx);


            }

            public void callService(ApplicationContext ctx) {
            // TODO Auto-generated method stub
            System.out.println("---callService---");
            System.out.println(myService);
            myService.callMydao();

            }

            }





            share|improve this answer














            If you are not coding a web application, make sure your class in which @Autowiring is done is a spring bean. Typically, spring container won't be aware of the class which we might think of as a spring bean. We have to tell the Spring container about our spring classes.



            This can be achieved by configuring in appln-contxt or the better way is to annotate class as @Component and please do not create the annotated class using new operator.
            Make sure you get it from Appln-context as below.



            @Component
            public class MyDemo {


            @Autowired
            private MyService myService;

            /**
            * @param args
            */
            public static void main(String args) {
            // TODO Auto-generated method stub
            System.out.println("test");
            ApplicationContext ctx=new ClassPathXmlApplicationContext("spring.xml");
            System.out.println("ctx>>"+ctx);

            Customer c1=null;
            MyDemo myDemo=ctx.getBean(MyDemo.class);
            System.out.println(myDemo);
            myDemo.callService(ctx);


            }

            public void callService(ApplicationContext ctx) {
            // TODO Auto-generated method stub
            System.out.println("---callService---");
            System.out.println(myService);
            myService.callMydao();

            }

            }






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jan 2 '16 at 15:01









            Andrew Morton

            15k53049




            15k53049










            answered Apr 22 '14 at 6:47









            Shirish Coolkarni

            56942




            56942












            • hi , I gone through your solution, that's correct . And Here I would like to know " Why we don't create instance of annotated class using new operator, may I know the reason behind that.
              – Ashish
              Dec 29 '14 at 11:30






            • 2




              if u create the object using new, u will be handling the life cycle of the bean which contradicts the concept of IOC. We need to ask the container to do it, which does it in a better way
              – Shirish Coolkarni
              Aug 20 '15 at 3:04


















            • hi , I gone through your solution, that's correct . And Here I would like to know " Why we don't create instance of annotated class using new operator, may I know the reason behind that.
              – Ashish
              Dec 29 '14 at 11:30






            • 2




              if u create the object using new, u will be handling the life cycle of the bean which contradicts the concept of IOC. We need to ask the container to do it, which does it in a better way
              – Shirish Coolkarni
              Aug 20 '15 at 3:04
















            hi , I gone through your solution, that's correct . And Here I would like to know " Why we don't create instance of annotated class using new operator, may I know the reason behind that.
            – Ashish
            Dec 29 '14 at 11:30




            hi , I gone through your solution, that's correct . And Here I would like to know " Why we don't create instance of annotated class using new operator, may I know the reason behind that.
            – Ashish
            Dec 29 '14 at 11:30




            2




            2




            if u create the object using new, u will be handling the life cycle of the bean which contradicts the concept of IOC. We need to ask the container to do it, which does it in a better way
            – Shirish Coolkarni
            Aug 20 '15 at 3:04




            if u create the object using new, u will be handling the life cycle of the bean which contradicts the concept of IOC. We need to ask the container to do it, which does it in a better way
            – Shirish Coolkarni
            Aug 20 '15 at 3:04










            up vote
            24
            down vote













            Actually, you should use either JVM managed Objects or Spring-managed Object to invoke methods.
            from your above code in your controller class, you are creating a new object to call your service class which has an auto-wired object.



            MileageFeeCalculator calc = new MileageFeeCalculator();


            so it won't work that way.



            The solution makes this MileageFeeCalculator as an auto-wired object in the Controller itself.



            Change your Controller class like below.



            @Controller
            public class MileageFeeController {

            @Autowired
            MileageFeeCalculator calc;

            @RequestMapping("/mileage/{miles}")
            @ResponseBody
            public float mileageFee(@PathVariable int miles) {
            return calc.mileageCharge(miles);
            }
            }





            share|improve this answer



















            • 1




              This is the answer. Because you're instantiating a new MilageFeeCalculator on your own, Spring isn't involved in the instantiation, so Spring spring has no knowledge the object exists. Thus, it can't do anything to it, like inject dependencies.
              – Robert Greathouse
              Sep 19 '17 at 17:27















            up vote
            24
            down vote













            Actually, you should use either JVM managed Objects or Spring-managed Object to invoke methods.
            from your above code in your controller class, you are creating a new object to call your service class which has an auto-wired object.



            MileageFeeCalculator calc = new MileageFeeCalculator();


            so it won't work that way.



            The solution makes this MileageFeeCalculator as an auto-wired object in the Controller itself.



            Change your Controller class like below.



            @Controller
            public class MileageFeeController {

            @Autowired
            MileageFeeCalculator calc;

            @RequestMapping("/mileage/{miles}")
            @ResponseBody
            public float mileageFee(@PathVariable int miles) {
            return calc.mileageCharge(miles);
            }
            }





            share|improve this answer



















            • 1




              This is the answer. Because you're instantiating a new MilageFeeCalculator on your own, Spring isn't involved in the instantiation, so Spring spring has no knowledge the object exists. Thus, it can't do anything to it, like inject dependencies.
              – Robert Greathouse
              Sep 19 '17 at 17:27













            up vote
            24
            down vote










            up vote
            24
            down vote









            Actually, you should use either JVM managed Objects or Spring-managed Object to invoke methods.
            from your above code in your controller class, you are creating a new object to call your service class which has an auto-wired object.



            MileageFeeCalculator calc = new MileageFeeCalculator();


            so it won't work that way.



            The solution makes this MileageFeeCalculator as an auto-wired object in the Controller itself.



            Change your Controller class like below.



            @Controller
            public class MileageFeeController {

            @Autowired
            MileageFeeCalculator calc;

            @RequestMapping("/mileage/{miles}")
            @ResponseBody
            public float mileageFee(@PathVariable int miles) {
            return calc.mileageCharge(miles);
            }
            }





            share|improve this answer














            Actually, you should use either JVM managed Objects or Spring-managed Object to invoke methods.
            from your above code in your controller class, you are creating a new object to call your service class which has an auto-wired object.



            MileageFeeCalculator calc = new MileageFeeCalculator();


            so it won't work that way.



            The solution makes this MileageFeeCalculator as an auto-wired object in the Controller itself.



            Change your Controller class like below.



            @Controller
            public class MileageFeeController {

            @Autowired
            MileageFeeCalculator calc;

            @RequestMapping("/mileage/{miles}")
            @ResponseBody
            public float mileageFee(@PathVariable int miles) {
            return calc.mileageCharge(miles);
            }
            }






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jul 26 at 19:21









            KIN

            40749




            40749










            answered Jul 26 '16 at 9:25









            Ravi Durairaj

            47134




            47134








            • 1




              This is the answer. Because you're instantiating a new MilageFeeCalculator on your own, Spring isn't involved in the instantiation, so Spring spring has no knowledge the object exists. Thus, it can't do anything to it, like inject dependencies.
              – Robert Greathouse
              Sep 19 '17 at 17:27














            • 1




              This is the answer. Because you're instantiating a new MilageFeeCalculator on your own, Spring isn't involved in the instantiation, so Spring spring has no knowledge the object exists. Thus, it can't do anything to it, like inject dependencies.
              – Robert Greathouse
              Sep 19 '17 at 17:27








            1




            1




            This is the answer. Because you're instantiating a new MilageFeeCalculator on your own, Spring isn't involved in the instantiation, so Spring spring has no knowledge the object exists. Thus, it can't do anything to it, like inject dependencies.
            – Robert Greathouse
            Sep 19 '17 at 17:27




            This is the answer. Because you're instantiating a new MilageFeeCalculator on your own, Spring isn't involved in the instantiation, so Spring spring has no knowledge the object exists. Thus, it can't do anything to it, like inject dependencies.
            – Robert Greathouse
            Sep 19 '17 at 17:27










            up vote
            21
            down vote













            I once encountered the same issue when I was not quite used to the life in the IoC world. The @Autowired field of one of my beans is null at runtime.



            The root cause is, instead of using the auto-created bean maintained by the Spring IoC container (whose @Autowired field is indeed properly injected), I am newing my own instance of that bean type and using it. Of course this one's @Autowired field is null because Spring has no chance to inject it.






            share|improve this answer



























              up vote
              21
              down vote













              I once encountered the same issue when I was not quite used to the life in the IoC world. The @Autowired field of one of my beans is null at runtime.



              The root cause is, instead of using the auto-created bean maintained by the Spring IoC container (whose @Autowired field is indeed properly injected), I am newing my own instance of that bean type and using it. Of course this one's @Autowired field is null because Spring has no chance to inject it.






              share|improve this answer

























                up vote
                21
                down vote










                up vote
                21
                down vote









                I once encountered the same issue when I was not quite used to the life in the IoC world. The @Autowired field of one of my beans is null at runtime.



                The root cause is, instead of using the auto-created bean maintained by the Spring IoC container (whose @Autowired field is indeed properly injected), I am newing my own instance of that bean type and using it. Of course this one's @Autowired field is null because Spring has no chance to inject it.






                share|improve this answer














                I once encountered the same issue when I was not quite used to the life in the IoC world. The @Autowired field of one of my beans is null at runtime.



                The root cause is, instead of using the auto-created bean maintained by the Spring IoC container (whose @Autowired field is indeed properly injected), I am newing my own instance of that bean type and using it. Of course this one's @Autowired field is null because Spring has no chance to inject it.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited May 3 '16 at 8:46

























                answered Nov 12 '15 at 13:41









                smwikipedia

                20.5k61208363




                20.5k61208363






















                    up vote
                    17
                    down vote













                    Your problem is new (object creation in java style)



                    MileageFeeCalculator calc = new MileageFeeCalculator();


                    With annotation @Service, @Component, @Configuration beans are created in the

                    application context of Spring when server is started. But when we create objects
                    using new operator the object is not registered in application context which is already created. For Example Employee.java class i have used.



                    Check this out:



                    public class ConfiguredTenantScopedBeanProcessor implements BeanFactoryPostProcessor {

                    @Override
                    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
                    String name = "tenant";
                    System.out.println("Bean factory post processor is initialized");
                    beanFactory.registerScope("employee", new Employee());

                    Assert.state(beanFactory instanceof BeanDefinitionRegistry,
                    "BeanFactory was not a BeanDefinitionRegistry, so CustomScope cannot be used.");
                    BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;

                    for (String beanName : beanFactory.getBeanDefinitionNames()) {
                    BeanDefinition definition = beanFactory.getBeanDefinition(beanName);
                    if (name.equals(definition.getScope())) {
                    BeanDefinitionHolder proxyHolder = ScopedProxyUtils.createScopedProxy(new BeanDefinitionHolder(definition, beanName), registry, true);
                    registry.registerBeanDefinition(beanName, proxyHolder.getBeanDefinition());
                    }
                    }
                    }

                    }





                    share|improve this answer



























                      up vote
                      17
                      down vote













                      Your problem is new (object creation in java style)



                      MileageFeeCalculator calc = new MileageFeeCalculator();


                      With annotation @Service, @Component, @Configuration beans are created in the

                      application context of Spring when server is started. But when we create objects
                      using new operator the object is not registered in application context which is already created. For Example Employee.java class i have used.



                      Check this out:



                      public class ConfiguredTenantScopedBeanProcessor implements BeanFactoryPostProcessor {

                      @Override
                      public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
                      String name = "tenant";
                      System.out.println("Bean factory post processor is initialized");
                      beanFactory.registerScope("employee", new Employee());

                      Assert.state(beanFactory instanceof BeanDefinitionRegistry,
                      "BeanFactory was not a BeanDefinitionRegistry, so CustomScope cannot be used.");
                      BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;

                      for (String beanName : beanFactory.getBeanDefinitionNames()) {
                      BeanDefinition definition = beanFactory.getBeanDefinition(beanName);
                      if (name.equals(definition.getScope())) {
                      BeanDefinitionHolder proxyHolder = ScopedProxyUtils.createScopedProxy(new BeanDefinitionHolder(definition, beanName), registry, true);
                      registry.registerBeanDefinition(beanName, proxyHolder.getBeanDefinition());
                      }
                      }
                      }

                      }





                      share|improve this answer

























                        up vote
                        17
                        down vote










                        up vote
                        17
                        down vote









                        Your problem is new (object creation in java style)



                        MileageFeeCalculator calc = new MileageFeeCalculator();


                        With annotation @Service, @Component, @Configuration beans are created in the

                        application context of Spring when server is started. But when we create objects
                        using new operator the object is not registered in application context which is already created. For Example Employee.java class i have used.



                        Check this out:



                        public class ConfiguredTenantScopedBeanProcessor implements BeanFactoryPostProcessor {

                        @Override
                        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
                        String name = "tenant";
                        System.out.println("Bean factory post processor is initialized");
                        beanFactory.registerScope("employee", new Employee());

                        Assert.state(beanFactory instanceof BeanDefinitionRegistry,
                        "BeanFactory was not a BeanDefinitionRegistry, so CustomScope cannot be used.");
                        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;

                        for (String beanName : beanFactory.getBeanDefinitionNames()) {
                        BeanDefinition definition = beanFactory.getBeanDefinition(beanName);
                        if (name.equals(definition.getScope())) {
                        BeanDefinitionHolder proxyHolder = ScopedProxyUtils.createScopedProxy(new BeanDefinitionHolder(definition, beanName), registry, true);
                        registry.registerBeanDefinition(beanName, proxyHolder.getBeanDefinition());
                        }
                        }
                        }

                        }





                        share|improve this answer














                        Your problem is new (object creation in java style)



                        MileageFeeCalculator calc = new MileageFeeCalculator();


                        With annotation @Service, @Component, @Configuration beans are created in the

                        application context of Spring when server is started. But when we create objects
                        using new operator the object is not registered in application context which is already created. For Example Employee.java class i have used.



                        Check this out:



                        public class ConfiguredTenantScopedBeanProcessor implements BeanFactoryPostProcessor {

                        @Override
                        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
                        String name = "tenant";
                        System.out.println("Bean factory post processor is initialized");
                        beanFactory.registerScope("employee", new Employee());

                        Assert.state(beanFactory instanceof BeanDefinitionRegistry,
                        "BeanFactory was not a BeanDefinitionRegistry, so CustomScope cannot be used.");
                        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;

                        for (String beanName : beanFactory.getBeanDefinitionNames()) {
                        BeanDefinition definition = beanFactory.getBeanDefinition(beanName);
                        if (name.equals(definition.getScope())) {
                        BeanDefinitionHolder proxyHolder = ScopedProxyUtils.createScopedProxy(new BeanDefinitionHolder(definition, beanName), registry, true);
                        registry.registerBeanDefinition(beanName, proxyHolder.getBeanDefinition());
                        }
                        }
                        }

                        }






                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Apr 12 at 10:43









                        Ahmed Ashour

                        3,470102442




                        3,470102442










                        answered Oct 8 '15 at 9:17









                        Deepak

                        1,0051218




                        1,0051218






















                            up vote
                            8
                            down vote













                            It seems to be rare case but here is what happened to me:



                            We used @Inject instead of @Autowired which is javaee standard supported by Spring. Every places it worked fine and the beans injected correctly, instead of one place. The bean injection seems the same



                            @Inject
                            Calculator myCalculator


                            At last we found that the error was that we (actually, the Eclipse auto complete feature) imported com.opensymphony.xwork2.Inject instead of javax.inject.Inject !



                            So to summarize, make sure that your annotations (@Autowired, @Inject, @Service ,... ) have correct packages!






                            share|improve this answer



























                              up vote
                              8
                              down vote













                              It seems to be rare case but here is what happened to me:



                              We used @Inject instead of @Autowired which is javaee standard supported by Spring. Every places it worked fine and the beans injected correctly, instead of one place. The bean injection seems the same



                              @Inject
                              Calculator myCalculator


                              At last we found that the error was that we (actually, the Eclipse auto complete feature) imported com.opensymphony.xwork2.Inject instead of javax.inject.Inject !



                              So to summarize, make sure that your annotations (@Autowired, @Inject, @Service ,... ) have correct packages!






                              share|improve this answer

























                                up vote
                                8
                                down vote










                                up vote
                                8
                                down vote









                                It seems to be rare case but here is what happened to me:



                                We used @Inject instead of @Autowired which is javaee standard supported by Spring. Every places it worked fine and the beans injected correctly, instead of one place. The bean injection seems the same



                                @Inject
                                Calculator myCalculator


                                At last we found that the error was that we (actually, the Eclipse auto complete feature) imported com.opensymphony.xwork2.Inject instead of javax.inject.Inject !



                                So to summarize, make sure that your annotations (@Autowired, @Inject, @Service ,... ) have correct packages!






                                share|improve this answer














                                It seems to be rare case but here is what happened to me:



                                We used @Inject instead of @Autowired which is javaee standard supported by Spring. Every places it worked fine and the beans injected correctly, instead of one place. The bean injection seems the same



                                @Inject
                                Calculator myCalculator


                                At last we found that the error was that we (actually, the Eclipse auto complete feature) imported com.opensymphony.xwork2.Inject instead of javax.inject.Inject !



                                So to summarize, make sure that your annotations (@Autowired, @Inject, @Service ,... ) have correct packages!







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Apr 20 at 13:07









                                TwiN

                                1,6911619




                                1,6911619










                                answered Jun 11 '16 at 15:15









                                Alireza Fattahi

                                20.2k86589




                                20.2k86589






















                                    up vote
                                    7
                                    down vote













                                    I'm new to Spring, but I discovered this working solution. Please tell me if it's a deprecable way.



                                    I make Spring inject applicationContext in this bean:



                                    import org.springframework.beans.factory.annotation.Autowired;
                                    import org.springframework.context.ApplicationContext;
                                    import org.springframework.stereotype.Component;

                                    @Component
                                    public class SpringUtils {

                                    public static ApplicationContext ctx;

                                    /**
                                    * Make Spring inject the application context
                                    * and save it on a static variable,
                                    * so that it can be accessed from any point in the application.
                                    */
                                    @Autowired
                                    private void setApplicationContext(ApplicationContext applicationContext) {
                                    ctx = applicationContext;
                                    }
                                    }


                                    You can put this code also in the main application class if you want.



                                    Other classes can use it like this:



                                    MyBean myBean = (MyBean)SpringUtils.ctx.getBean(MyBean.class);


                                    In this way any bean can be obtained by any object in the application (also intantiated with new) and in a static way.






                                    share|improve this answer





















                                    • This pattern is necessary to make Spring beans accessible to legacy code but should be avoided in new code.
                                      – chrylis
                                      May 14 '15 at 13:06















                                    up vote
                                    7
                                    down vote













                                    I'm new to Spring, but I discovered this working solution. Please tell me if it's a deprecable way.



                                    I make Spring inject applicationContext in this bean:



                                    import org.springframework.beans.factory.annotation.Autowired;
                                    import org.springframework.context.ApplicationContext;
                                    import org.springframework.stereotype.Component;

                                    @Component
                                    public class SpringUtils {

                                    public static ApplicationContext ctx;

                                    /**
                                    * Make Spring inject the application context
                                    * and save it on a static variable,
                                    * so that it can be accessed from any point in the application.
                                    */
                                    @Autowired
                                    private void setApplicationContext(ApplicationContext applicationContext) {
                                    ctx = applicationContext;
                                    }
                                    }


                                    You can put this code also in the main application class if you want.



                                    Other classes can use it like this:



                                    MyBean myBean = (MyBean)SpringUtils.ctx.getBean(MyBean.class);


                                    In this way any bean can be obtained by any object in the application (also intantiated with new) and in a static way.






                                    share|improve this answer





















                                    • This pattern is necessary to make Spring beans accessible to legacy code but should be avoided in new code.
                                      – chrylis
                                      May 14 '15 at 13:06













                                    up vote
                                    7
                                    down vote










                                    up vote
                                    7
                                    down vote









                                    I'm new to Spring, but I discovered this working solution. Please tell me if it's a deprecable way.



                                    I make Spring inject applicationContext in this bean:



                                    import org.springframework.beans.factory.annotation.Autowired;
                                    import org.springframework.context.ApplicationContext;
                                    import org.springframework.stereotype.Component;

                                    @Component
                                    public class SpringUtils {

                                    public static ApplicationContext ctx;

                                    /**
                                    * Make Spring inject the application context
                                    * and save it on a static variable,
                                    * so that it can be accessed from any point in the application.
                                    */
                                    @Autowired
                                    private void setApplicationContext(ApplicationContext applicationContext) {
                                    ctx = applicationContext;
                                    }
                                    }


                                    You can put this code also in the main application class if you want.



                                    Other classes can use it like this:



                                    MyBean myBean = (MyBean)SpringUtils.ctx.getBean(MyBean.class);


                                    In this way any bean can be obtained by any object in the application (also intantiated with new) and in a static way.






                                    share|improve this answer












                                    I'm new to Spring, but I discovered this working solution. Please tell me if it's a deprecable way.



                                    I make Spring inject applicationContext in this bean:



                                    import org.springframework.beans.factory.annotation.Autowired;
                                    import org.springframework.context.ApplicationContext;
                                    import org.springframework.stereotype.Component;

                                    @Component
                                    public class SpringUtils {

                                    public static ApplicationContext ctx;

                                    /**
                                    * Make Spring inject the application context
                                    * and save it on a static variable,
                                    * so that it can be accessed from any point in the application.
                                    */
                                    @Autowired
                                    private void setApplicationContext(ApplicationContext applicationContext) {
                                    ctx = applicationContext;
                                    }
                                    }


                                    You can put this code also in the main application class if you want.



                                    Other classes can use it like this:



                                    MyBean myBean = (MyBean)SpringUtils.ctx.getBean(MyBean.class);


                                    In this way any bean can be obtained by any object in the application (also intantiated with new) and in a static way.







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered May 14 '15 at 12:44









                                    bluish

                                    13.6k1693146




                                    13.6k1693146












                                    • This pattern is necessary to make Spring beans accessible to legacy code but should be avoided in new code.
                                      – chrylis
                                      May 14 '15 at 13:06


















                                    • This pattern is necessary to make Spring beans accessible to legacy code but should be avoided in new code.
                                      – chrylis
                                      May 14 '15 at 13:06
















                                    This pattern is necessary to make Spring beans accessible to legacy code but should be avoided in new code.
                                    – chrylis
                                    May 14 '15 at 13:06




                                    This pattern is necessary to make Spring beans accessible to legacy code but should be avoided in new code.
                                    – chrylis
                                    May 14 '15 at 13:06










                                    up vote
                                    3
                                    down vote













                                    I think you have missed to instruct spring to scan classes with annotation.



                                    You can use @ComponentScan("packageToScan") on the configuration class of your spring application to instruct spring to scan.



                                    @Service, @Component etc annotations add meta description.



                                    Spring only injects instances of those classes which are either created as bean or marked with annotation.



                                    Classes marked with annotation need to be identified by spring before injecting, @ComponentScan instruct spring look for the classes marked with annotation. When Spring finds @Autowired it searches for the related bean, and injects the required instance.



                                    Adding annotation only, does not fix or facilitate the dependency injection, Spring needs to know where to look for.






                                    share|improve this answer



























                                      up vote
                                      3
                                      down vote













                                      I think you have missed to instruct spring to scan classes with annotation.



                                      You can use @ComponentScan("packageToScan") on the configuration class of your spring application to instruct spring to scan.



                                      @Service, @Component etc annotations add meta description.



                                      Spring only injects instances of those classes which are either created as bean or marked with annotation.



                                      Classes marked with annotation need to be identified by spring before injecting, @ComponentScan instruct spring look for the classes marked with annotation. When Spring finds @Autowired it searches for the related bean, and injects the required instance.



                                      Adding annotation only, does not fix or facilitate the dependency injection, Spring needs to know where to look for.






                                      share|improve this answer

























                                        up vote
                                        3
                                        down vote










                                        up vote
                                        3
                                        down vote









                                        I think you have missed to instruct spring to scan classes with annotation.



                                        You can use @ComponentScan("packageToScan") on the configuration class of your spring application to instruct spring to scan.



                                        @Service, @Component etc annotations add meta description.



                                        Spring only injects instances of those classes which are either created as bean or marked with annotation.



                                        Classes marked with annotation need to be identified by spring before injecting, @ComponentScan instruct spring look for the classes marked with annotation. When Spring finds @Autowired it searches for the related bean, and injects the required instance.



                                        Adding annotation only, does not fix or facilitate the dependency injection, Spring needs to know where to look for.






                                        share|improve this answer














                                        I think you have missed to instruct spring to scan classes with annotation.



                                        You can use @ComponentScan("packageToScan") on the configuration class of your spring application to instruct spring to scan.



                                        @Service, @Component etc annotations add meta description.



                                        Spring only injects instances of those classes which are either created as bean or marked with annotation.



                                        Classes marked with annotation need to be identified by spring before injecting, @ComponentScan instruct spring look for the classes marked with annotation. When Spring finds @Autowired it searches for the related bean, and injects the required instance.



                                        Adding annotation only, does not fix or facilitate the dependency injection, Spring needs to know where to look for.







                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Jan 10 '17 at 19:34









                                        Newd

                                        2,04421330




                                        2,04421330










                                        answered Jan 10 '17 at 18:00









                                        msucil

                                        1811110




                                        1811110






















                                            up vote
                                            2
                                            down vote













                                            Another solution would be putting call:
                                            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this)

                                            To MileageFeeCalculator constructor like this:



                                            @Service
                                            public class MileageFeeCalculator {

                                            @Autowired
                                            private MileageRateService rateService; // <--- will be autowired when constructor is called

                                            public MileageFeeCalculator() {
                                            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this)
                                            }

                                            public float mileageCharge(final int miles) {
                                            return (miles * rateService.ratePerMile());
                                            }
                                            }





                                            share|improve this answer























                                            • This uses unsafe publication.
                                              – chrylis
                                              Apr 21 '15 at 12:41















                                            up vote
                                            2
                                            down vote













                                            Another solution would be putting call:
                                            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this)

                                            To MileageFeeCalculator constructor like this:



                                            @Service
                                            public class MileageFeeCalculator {

                                            @Autowired
                                            private MileageRateService rateService; // <--- will be autowired when constructor is called

                                            public MileageFeeCalculator() {
                                            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this)
                                            }

                                            public float mileageCharge(final int miles) {
                                            return (miles * rateService.ratePerMile());
                                            }
                                            }





                                            share|improve this answer























                                            • This uses unsafe publication.
                                              – chrylis
                                              Apr 21 '15 at 12:41













                                            up vote
                                            2
                                            down vote










                                            up vote
                                            2
                                            down vote









                                            Another solution would be putting call:
                                            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this)

                                            To MileageFeeCalculator constructor like this:



                                            @Service
                                            public class MileageFeeCalculator {

                                            @Autowired
                                            private MileageRateService rateService; // <--- will be autowired when constructor is called

                                            public MileageFeeCalculator() {
                                            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this)
                                            }

                                            public float mileageCharge(final int miles) {
                                            return (miles * rateService.ratePerMile());
                                            }
                                            }





                                            share|improve this answer














                                            Another solution would be putting call:
                                            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this)

                                            To MileageFeeCalculator constructor like this:



                                            @Service
                                            public class MileageFeeCalculator {

                                            @Autowired
                                            private MileageRateService rateService; // <--- will be autowired when constructor is called

                                            public MileageFeeCalculator() {
                                            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this)
                                            }

                                            public float mileageCharge(final int miles) {
                                            return (miles * rateService.ratePerMile());
                                            }
                                            }






                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            edited Apr 21 '15 at 11:42

























                                            answered Apr 21 '15 at 11:35









                                            Ondrej Bozek

                                            5,98933760




                                            5,98933760












                                            • This uses unsafe publication.
                                              – chrylis
                                              Apr 21 '15 at 12:41


















                                            • This uses unsafe publication.
                                              – chrylis
                                              Apr 21 '15 at 12:41
















                                            This uses unsafe publication.
                                            – chrylis
                                            Apr 21 '15 at 12:41




                                            This uses unsafe publication.
                                            – chrylis
                                            Apr 21 '15 at 12:41










                                            up vote
                                            2
                                            down vote













                                            You can also fix this issue using @Service annotation on service class and passing the required bean classA as a parameter to the other beans classB constructor and annotate the constructor of classB with @Autowired. Sample snippet here :



                                            @Service
                                            public class ClassB {

                                            private ClassA classA;

                                            @Autowired
                                            public ClassB(ClassA classA) {
                                            this.classA = classA;
                                            }

                                            public void useClassAObjectHere(){
                                            classA.callMethodOnObjectA();
                                            }
                                            }





                                            share|improve this answer























                                            • this worked for me bu t can you please elaborate on how this is solving the issue ?
                                              – CruelEngine
                                              Mar 5 at 12:58






                                            • 1




                                              @CruelEngine, look this is constructor injection (where you explicitly setting an object) instead of just using field injection (this is mostly done by spring configuration mostly). So if you are creating a object of ClassB using "new" operator is some other scope then that would not be visible or autowired set for ClassA. Hence, while calling classB.useClassAObjectHere() would throw NPE as classA object was not autowired if you just declare field Injection. Read chrylis is trying to explain same. And this why constructor injection is recommended over field injection. Does it make sense now ?
                                              – apandey846
                                              Apr 11 at 8:45










                                            • now i get it . thanks :)
                                              – CruelEngine
                                              Apr 11 at 12:28















                                            up vote
                                            2
                                            down vote













                                            You can also fix this issue using @Service annotation on service class and passing the required bean classA as a parameter to the other beans classB constructor and annotate the constructor of classB with @Autowired. Sample snippet here :



                                            @Service
                                            public class ClassB {

                                            private ClassA classA;

                                            @Autowired
                                            public ClassB(ClassA classA) {
                                            this.classA = classA;
                                            }

                                            public void useClassAObjectHere(){
                                            classA.callMethodOnObjectA();
                                            }
                                            }





                                            share|improve this answer























                                            • this worked for me bu t can you please elaborate on how this is solving the issue ?
                                              – CruelEngine
                                              Mar 5 at 12:58






                                            • 1




                                              @CruelEngine, look this is constructor injection (where you explicitly setting an object) instead of just using field injection (this is mostly done by spring configuration mostly). So if you are creating a object of ClassB using "new" operator is some other scope then that would not be visible or autowired set for ClassA. Hence, while calling classB.useClassAObjectHere() would throw NPE as classA object was not autowired if you just declare field Injection. Read chrylis is trying to explain same. And this why constructor injection is recommended over field injection. Does it make sense now ?
                                              – apandey846
                                              Apr 11 at 8:45










                                            • now i get it . thanks :)
                                              – CruelEngine
                                              Apr 11 at 12:28













                                            up vote
                                            2
                                            down vote










                                            up vote
                                            2
                                            down vote









                                            You can also fix this issue using @Service annotation on service class and passing the required bean classA as a parameter to the other beans classB constructor and annotate the constructor of classB with @Autowired. Sample snippet here :



                                            @Service
                                            public class ClassB {

                                            private ClassA classA;

                                            @Autowired
                                            public ClassB(ClassA classA) {
                                            this.classA = classA;
                                            }

                                            public void useClassAObjectHere(){
                                            classA.callMethodOnObjectA();
                                            }
                                            }





                                            share|improve this answer














                                            You can also fix this issue using @Service annotation on service class and passing the required bean classA as a parameter to the other beans classB constructor and annotate the constructor of classB with @Autowired. Sample snippet here :



                                            @Service
                                            public class ClassB {

                                            private ClassA classA;

                                            @Autowired
                                            public ClassB(ClassA classA) {
                                            this.classA = classA;
                                            }

                                            public void useClassAObjectHere(){
                                            classA.callMethodOnObjectA();
                                            }
                                            }






                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            edited Oct 13 '16 at 18:56

























                                            answered Oct 13 '16 at 18:41









                                            apandey846

                                            832919




                                            832919












                                            • this worked for me bu t can you please elaborate on how this is solving the issue ?
                                              – CruelEngine
                                              Mar 5 at 12:58






                                            • 1




                                              @CruelEngine, look this is constructor injection (where you explicitly setting an object) instead of just using field injection (this is mostly done by spring configuration mostly). So if you are creating a object of ClassB using "new" operator is some other scope then that would not be visible or autowired set for ClassA. Hence, while calling classB.useClassAObjectHere() would throw NPE as classA object was not autowired if you just declare field Injection. Read chrylis is trying to explain same. And this why constructor injection is recommended over field injection. Does it make sense now ?
                                              – apandey846
                                              Apr 11 at 8:45










                                            • now i get it . thanks :)
                                              – CruelEngine
                                              Apr 11 at 12:28


















                                            • this worked for me bu t can you please elaborate on how this is solving the issue ?
                                              – CruelEngine
                                              Mar 5 at 12:58






                                            • 1




                                              @CruelEngine, look this is constructor injection (where you explicitly setting an object) instead of just using field injection (this is mostly done by spring configuration mostly). So if you are creating a object of ClassB using "new" operator is some other scope then that would not be visible or autowired set for ClassA. Hence, while calling classB.useClassAObjectHere() would throw NPE as classA object was not autowired if you just declare field Injection. Read chrylis is trying to explain same. And this why constructor injection is recommended over field injection. Does it make sense now ?
                                              – apandey846
                                              Apr 11 at 8:45










                                            • now i get it . thanks :)
                                              – CruelEngine
                                              Apr 11 at 12:28
















                                            this worked for me bu t can you please elaborate on how this is solving the issue ?
                                            – CruelEngine
                                            Mar 5 at 12:58




                                            this worked for me bu t can you please elaborate on how this is solving the issue ?
                                            – CruelEngine
                                            Mar 5 at 12:58




                                            1




                                            1




                                            @CruelEngine, look this is constructor injection (where you explicitly setting an object) instead of just using field injection (this is mostly done by spring configuration mostly). So if you are creating a object of ClassB using "new" operator is some other scope then that would not be visible or autowired set for ClassA. Hence, while calling classB.useClassAObjectHere() would throw NPE as classA object was not autowired if you just declare field Injection. Read chrylis is trying to explain same. And this why constructor injection is recommended over field injection. Does it make sense now ?
                                            – apandey846
                                            Apr 11 at 8:45




                                            @CruelEngine, look this is constructor injection (where you explicitly setting an object) instead of just using field injection (this is mostly done by spring configuration mostly). So if you are creating a object of ClassB using "new" operator is some other scope then that would not be visible or autowired set for ClassA. Hence, while calling classB.useClassAObjectHere() would throw NPE as classA object was not autowired if you just declare field Injection. Read chrylis is trying to explain same. And this why constructor injection is recommended over field injection. Does it make sense now ?
                                            – apandey846
                                            Apr 11 at 8:45












                                            now i get it . thanks :)
                                            – CruelEngine
                                            Apr 11 at 12:28




                                            now i get it . thanks :)
                                            – CruelEngine
                                            Apr 11 at 12:28










                                            up vote
                                            2
                                            down vote













                                            UPDATE: Really smart people were quick to point on this answer, which explains the weirdness, described below



                                            ORIGINAL ANSWER:



                                            I don't know if it helps anyone, but I was stuck with the same problem even while doing things seemingly right. In my Main method, I have a code like this:



                                            ApplicationContext context =
                                            new ClassPathXmlApplicationContext(new String {
                                            "common.xml",
                                            "token.xml",
                                            "pep-config.xml" });
                                            TokenInitializer ti = context.getBean(TokenInitializer.class);


                                            and in a token.xml file I've had a line



                                            <context:component-scan base-package="package.path"/>


                                            I noticed that the package.path does no longer exist, so I've just dropped the line for good.



                                            And after that, NPE started coming in. In a pep-config.xml I had just 2 beans:



                                            <bean id="someAbac" class="com.pep.SomeAbac" init-method="init"/>
                                            <bean id="settings" class="com.pep.Settings"/>


                                            and SomeAbac class has a property declared as



                                            @Autowired private Settings settings;


                                            for some unknown reason, settings is null in init(), when <context:component-scan/> element is not present at all, but when it's present and has some bs as a basePackage, everything works well. This line now looks like this:



                                            <context:component-scan base-package="some.shit"/>


                                            and it works. May be someone can provide an explanation, but for me it's enough right now )






                                            share|improve this answer



















                                            • 4




                                              That answer is the explanation. <context:component-scan/> implicitly enables <context:annotation-config/> necessary for the @Autowired to work.
                                              – ForNeVeR
                                              Oct 12 '17 at 4:55

















                                            up vote
                                            2
                                            down vote













                                            UPDATE: Really smart people were quick to point on this answer, which explains the weirdness, described below



                                            ORIGINAL ANSWER:



                                            I don't know if it helps anyone, but I was stuck with the same problem even while doing things seemingly right. In my Main method, I have a code like this:



                                            ApplicationContext context =
                                            new ClassPathXmlApplicationContext(new String {
                                            "common.xml",
                                            "token.xml",
                                            "pep-config.xml" });
                                            TokenInitializer ti = context.getBean(TokenInitializer.class);


                                            and in a token.xml file I've had a line



                                            <context:component-scan base-package="package.path"/>


                                            I noticed that the package.path does no longer exist, so I've just dropped the line for good.



                                            And after that, NPE started coming in. In a pep-config.xml I had just 2 beans:



                                            <bean id="someAbac" class="com.pep.SomeAbac" init-method="init"/>
                                            <bean id="settings" class="com.pep.Settings"/>


                                            and SomeAbac class has a property declared as



                                            @Autowired private Settings settings;


                                            for some unknown reason, settings is null in init(), when <context:component-scan/> element is not present at all, but when it's present and has some bs as a basePackage, everything works well. This line now looks like this:



                                            <context:component-scan base-package="some.shit"/>


                                            and it works. May be someone can provide an explanation, but for me it's enough right now )






                                            share|improve this answer



















                                            • 4




                                              That answer is the explanation. <context:component-scan/> implicitly enables <context:annotation-config/> necessary for the @Autowired to work.
                                              – ForNeVeR
                                              Oct 12 '17 at 4:55















                                            up vote
                                            2
                                            down vote










                                            up vote
                                            2
                                            down vote









                                            UPDATE: Really smart people were quick to point on this answer, which explains the weirdness, described below



                                            ORIGINAL ANSWER:



                                            I don't know if it helps anyone, but I was stuck with the same problem even while doing things seemingly right. In my Main method, I have a code like this:



                                            ApplicationContext context =
                                            new ClassPathXmlApplicationContext(new String {
                                            "common.xml",
                                            "token.xml",
                                            "pep-config.xml" });
                                            TokenInitializer ti = context.getBean(TokenInitializer.class);


                                            and in a token.xml file I've had a line



                                            <context:component-scan base-package="package.path"/>


                                            I noticed that the package.path does no longer exist, so I've just dropped the line for good.



                                            And after that, NPE started coming in. In a pep-config.xml I had just 2 beans:



                                            <bean id="someAbac" class="com.pep.SomeAbac" init-method="init"/>
                                            <bean id="settings" class="com.pep.Settings"/>


                                            and SomeAbac class has a property declared as



                                            @Autowired private Settings settings;


                                            for some unknown reason, settings is null in init(), when <context:component-scan/> element is not present at all, but when it's present and has some bs as a basePackage, everything works well. This line now looks like this:



                                            <context:component-scan base-package="some.shit"/>


                                            and it works. May be someone can provide an explanation, but for me it's enough right now )






                                            share|improve this answer














                                            UPDATE: Really smart people were quick to point on this answer, which explains the weirdness, described below



                                            ORIGINAL ANSWER:



                                            I don't know if it helps anyone, but I was stuck with the same problem even while doing things seemingly right. In my Main method, I have a code like this:



                                            ApplicationContext context =
                                            new ClassPathXmlApplicationContext(new String {
                                            "common.xml",
                                            "token.xml",
                                            "pep-config.xml" });
                                            TokenInitializer ti = context.getBean(TokenInitializer.class);


                                            and in a token.xml file I've had a line



                                            <context:component-scan base-package="package.path"/>


                                            I noticed that the package.path does no longer exist, so I've just dropped the line for good.



                                            And after that, NPE started coming in. In a pep-config.xml I had just 2 beans:



                                            <bean id="someAbac" class="com.pep.SomeAbac" init-method="init"/>
                                            <bean id="settings" class="com.pep.Settings"/>


                                            and SomeAbac class has a property declared as



                                            @Autowired private Settings settings;


                                            for some unknown reason, settings is null in init(), when <context:component-scan/> element is not present at all, but when it's present and has some bs as a basePackage, everything works well. This line now looks like this:



                                            <context:component-scan base-package="some.shit"/>


                                            and it works. May be someone can provide an explanation, but for me it's enough right now )







                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            edited Apr 12 at 10:42









                                            Ahmed Ashour

                                            3,470102442




                                            3,470102442










                                            answered Oct 12 '17 at 4:43









                                            62mkv

                                            505517




                                            505517








                                            • 4




                                              That answer is the explanation. <context:component-scan/> implicitly enables <context:annotation-config/> necessary for the @Autowired to work.
                                              – ForNeVeR
                                              Oct 12 '17 at 4:55
















                                            • 4




                                              That answer is the explanation. <context:component-scan/> implicitly enables <context:annotation-config/> necessary for the @Autowired to work.
                                              – ForNeVeR
                                              Oct 12 '17 at 4:55










                                            4




                                            4




                                            That answer is the explanation. <context:component-scan/> implicitly enables <context:annotation-config/> necessary for the @Autowired to work.
                                            – ForNeVeR
                                            Oct 12 '17 at 4:55






                                            That answer is the explanation. <context:component-scan/> implicitly enables <context:annotation-config/> necessary for the @Autowired to work.
                                            – ForNeVeR
                                            Oct 12 '17 at 4:55












                                            up vote
                                            2
                                            down vote













                                            If this is happening in a test class, make sure you haven't forgotten to annotate the class.



                                            For example, in Spring Boot:



                                            @RunWith(SpringRunner.class)
                                            @SpringBootTest
                                            public class MyTests {
                                            ....





                                            share|improve this answer

























                                              up vote
                                              2
                                              down vote













                                              If this is happening in a test class, make sure you haven't forgotten to annotate the class.



                                              For example, in Spring Boot:



                                              @RunWith(SpringRunner.class)
                                              @SpringBootTest
                                              public class MyTests {
                                              ....





                                              share|improve this answer























                                                up vote
                                                2
                                                down vote










                                                up vote
                                                2
                                                down vote









                                                If this is happening in a test class, make sure you haven't forgotten to annotate the class.



                                                For example, in Spring Boot:



                                                @RunWith(SpringRunner.class)
                                                @SpringBootTest
                                                public class MyTests {
                                                ....





                                                share|improve this answer












                                                If this is happening in a test class, make sure you haven't forgotten to annotate the class.



                                                For example, in Spring Boot:



                                                @RunWith(SpringRunner.class)
                                                @SpringBootTest
                                                public class MyTests {
                                                ....






                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Apr 12 at 18:25









                                                nobar

                                                24.8k108497




                                                24.8k108497

















                                                    protected by chrylis May 8 '14 at 15:21



                                                    Thank you for your interest in this question.
                                                    Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                    Would you like to answer one of these unanswered questions instead?



                                                    Popular posts from this blog

                                                    Can a sorcerer learn a 5th-level spell early by creating spell slots using the Font of Magic feature?

                                                    Does disintegrating a polymorphed enemy still kill it after the 2018 errata?

                                                    A Topological Invariant for $pi_3(U(n))$