0

I would like to know what's the better things between these situations in therme of performance :

@Component
public class A{


    public void doSomethingOne(){

        ServiceDelegateA serviceA = (ServiceDelegateA) ApplicationContextUtils.getBean("ServiceDelegateA");         

        serviceA.compute();
    }


    public void doSomethingTwo(){

        ServiceDelegateB serviceB = (ServiceDelegateB) ApplicationContextUtils.getBean("ServiceDelegateB");         

        serviceB.doAction();
    }
}

Or

@Component
public class A{


    @Autowired
    ServiceDelegateA serviceA;

    @Autowired
    ServiceDelegateB serviceB;



    public void doSomethingOne(){
    serviceA.compute();

    }


    public void doSomethingTwo(){


        serviceB.doAction();
    }
}

Thank your in advance for help and your advices.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
user2049200
  • 127
  • 2
  • 10
  • 1
    What is `ApplicationContextUtils`? – Sotirios Delimanolis Jan 24 '14 at 01:49
  • Have a look at this http://stackoverflow.com/questions/812415/why-is-springs-applicationcontext-getbean-considered-bad – RP- Jan 24 '14 at 02:06
  • 1
    I would say that the difference is negligible, and if it truly matters, then you would measure it and make a call then. Your decision to adopt either approach should be driven by other factors (style, maintainability, vendor tie-in). Premature optimisation is the root of all evil – Romski Jan 24 '14 at 04:54

1 Answers1

0

I answer this question by assuming ApplicationContextUtils implements ApplicationContextAware and has a ApplicationContext inside of it.

Based on the spring documentation available here you can read the section Are annotations better than XML for configuring Spring? but as a comparison.

XML based Configuration;

  1. Can Work with Plain Old Java Objects (POJO) which doesn't have any annotations. Which means no additional dependencies in the Java Objects. The Source code is never touched for Spring Configuration and Source Code can be reused in other places.
  2. This approach is better when you work with Pre-compiled Jar files where you can not modify and recompile source code to have annotations or you want your codes to be backward compatible with different JVMs.
  3. Configurations are centralized and easy to maintain

Annotation based Configuration;

  1. All Spring related Configurations are in the Java Object itself so the Configuration is clean and concise.
  2. Configurations are decentralized and sometimes hard to maintain.
  3. The Java Classes are no longer POJOs.

Both approaches have their pros and cons but it is upto the developer to decide the correct approach for their needs.

shazin
  • 21,379
  • 3
  • 54
  • 71