Announcement Announcement Module
Collapse
No announcement yet.
Injecting into a static variable Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Injecting into a static variable

    Guys,
    I'm starting a project where I'd like to adopt a kind of 'Active record' approach.

    As such, I could end up with a domain class like this:

    Code:
    public class Person {
      private static Repository repo;
    
      public static void setRepository(Repository repo){/*set the repo*/}
    
      public static Peron load(int Id){use the static repo to load an instance of the class}
    
      /*normal instance methods*/
      public void save()...
      public void delete()...
    ...
    }
    I know I can dependency inject some bean into an object not managed by Spring, using @Configurable and turning on this capability. but that would mean I still need an instance (created by hibernate, for example) to have the repo configured.

    Is there a way to inject a dependency into a static field in the way I described. I thought that something of AOP may do.... I am not an expert on this area, so any thoughts are welcome.

    Thanks a lot,
    Leo.

  • #2
    The MethodInvokingFactoryBean is your friend:

    http://www.springframework.org/docs/...ctoryBean.html

    example:
    Code:
        <bean id="loadBcProvider"
              class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
            <property name="staticMethod"
                      value="java.security.Security.addProvider"/>
            <property name="arguments">
                <list>
                    <bean class="org.bouncycastle.jce.provider.BouncyCastleProvider"/>
                </list>
            </property>
        </bean>
    This calls:
    java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider ());

    But you could also create your own FactoryBean.

    Comment


    • #3
      Thanks man,
      That was exactly what I was looking for.

      C ya.

      Comment


      • #4
        Instantiating beans using instance factory method and static factory method should save some key strokes compared to MethodInvocationFactoryBean.

        Joerg

        Comment

        Working...
        X