Announcement Announcement Module
No announcement yet.
How to specify/make a bean as immutable in beanfactory Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • #16
    The point is how do you prevent them from using a "new" or "getInstance" without using "getBean" to create the bean?
    First, you can't prevent them from using new or a factory getInstance directly. Don't worry about it, because you can easily refactor a bean to instead receive what objects it needs.

    Second, why do you think the way you get a reference to an object is via applicationContext.getBean()????

    I have a small web application with maybe 70 or so beans and the only time I have used getBean is a few times in my integration testing code. (In production, none of the beans I created have any knowledge of Spring's core APIs) I get impression that you are not using inversion of control--and Spring's capabilities--to it's fullest yet. It appears that your beans are passed an ApplicationContext--why?

    The construction of your beans and 'injection' of their dependencies is defined in the context xml files! A bean doesn't have to have any knowledge that it is in a Spring environment. (If you pass the ApplicationContext to it then it would have knowledge of Spring interfaces) All a bean has to know is the interfaces of the objects it needs. Also a bean only has to provide a means for an outside agent--the Spring enviroment--to pass it the object instances it needs. This is done via a constructor or setter methods.

    Have you been passing your object dependencies in your xml files? For example:

    <property name="velocityEngine">
    In this case there is a property on some bean that has a method called setVelocityEngine( VelocityEngine ) And there is a bean defined somewhere else in context files that has the name or id of "velocityEngine" that is of type VelocityEngine.

    The bean in question doesn't know how the object it needs is constructed all it knows is it has a reference to an object of a certain type and knows how to call that objects interface.

    Your developers might follow a rule something like following:
    "Make sure your primary objects/services provide a means to receive all their dependencies"

    The actual construction/instantiation of these beans is handled by a third party--the IOC framework. The Spring framework wires all your system's objects together for you.

    While there might be situations where passing ApplicationContext make sense, I think passing an ApplicationContext should be done rarely.

    Regards, Jim