li jianmin
li jianmin

Reputation: 31

How can I ensure the loading order of Spring Beans?

I have a third party jar which provides a servlet filter used in my project. In the servlet filter there is a static block initializing a static object.

What I am doing is using reflection to retrieve the static object and revise it.

The configuration is as following:

<filter>
  <filter-name>thirdPartyFilter</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
  <filter-name>thirdPartyFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

Where thirdPartyFilter is defined in xml

<bean id="thirdPartyFilter" class="com.abc.ThirdPartyFilter" />

The ThirdPartyFilter in simple

class ThirdPartyFilter implements Filter{
    private static BB bb = new BB();
    static{
         bb.setText("bb");
    }
    doFilter(){...}
}

I already have a class called ThirdPartyFilterModifier,in which there is a factory bean using reflection to manipulate the object BB which is initialized in thirdPartyFilter. But the definition of the modifier is using annotation.

@configuration
class ThirdPartyFilterModifier{
   @Bean
   public BB reviseBB(){
      // using reflection to retrieve bb and revise it.
      return bb;
   }
}

Checking the console log while the app is starting, I can clearly see that the static block in ThirdPartyFilter printed out first, and then the factory bean of ThirdPartyFilterModifier comes later.

I admit this is the very result what I expect. But the thing confuses me a bit because I didn't do anything to ensure the thirdPartyFilter loaded before the thirdPartyFilterModifier.

Can anyone point out if I am doing the right thing in both the xml and annotation configuration?

//UPDATED I have just tried converting the annotation into xml

<bean id="thirdPartyFilterModifier" class="com.mycom.ThirdPartyFilterModifier" factory-method="reviseBB" />

and placed this definition before & after the thirdPartyFilter's. Got the same result of the ordering : firstly thirdPartyFilter and then thirdPartyFilterModifier.

Upvotes: 0

Views: 2990

Answers (1)

Gergely Bacso
Gergely Bacso

Reputation: 14651

If you just want to ensure the order of creation between any two beans managed by Spring, you can use depends-on.

In XML:

<bean id="beanOne" class="ExampleBean" depends-on="manager">
  <property name="manager" ref="manager" />
</bean>

In annotations:

@DependsOn

In general: modifying the a third-party filter via reflection does not sound like a good idea. If possible, you should try to find an alternative solution. Even after you make this work, you will be locked with that version of your dependency and cannot safely update to a newer version. Maybe it would be worth posting another SO question to find a cleaner solution.

Upvotes: 2

Related Questions