Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible from Spring to inject the result of calling a method on a ref bean?

Tags:

java

spring

Is it possible from Spring to inject the result of calling a method on a ref bean?

I'm trying to refactor some cut/pasted code from two separate projects into a common class. In one of the projects, the code lives in a class I'll call "MyClient" that is being instantiated from Spring. It is injected with another spring-instantiated class "MyRegistry", then the MyClient class uses that class to look up an endpoint. All I really need is the endpoint String in my refactored class, which can be initialized via a Setter. I really cannot have a dependency on MyRegistry from MyClient in the refactored code.

So, my question is this... is there a way I can inject the endpoint String from spring that was looked up in the MyRegistry class. So, I currently have:

<bean id="registryService" class="foo.MyRegistry"> ...properties set etc... </bean>  <bean id="MyClient" class="foo.MyClient">     <property name="registry" ref="registryService"/> </bean> 

But I'd like to have (and I know this is imaginary Spring syntax)

<bean id="MyClient" class="foo.MyClient">     <property name="endPoint" value="registryService.getEndPoint('bar')"/> </bean> 

where MyRegistry will have a method getEndPoint(Stirng endPointName)

Hope that makes sense from a the standpoint of what I'm trying to achieve. Please let me know if something like this is possible in Spring!

like image 985
Alex Worden Avatar asked Mar 26 '10 01:03

Alex Worden


People also ask

How do you inject Spring values?

Method 3 : Using @Value annotation This method involves applying @Value annotation over bean properties whose values are to be injected. The string provided along with the annotation may either be the value of the bean field or it may refer to a property name from a properties file loaded earlier in Spring context.

How do you call a bean in a Spring boot?

To declare a bean, simply annotate a method with the @Bean annotation. When JavaConfig encounters such a method, it will execute that method and register the return value as a bean within a BeanFactory .

How do you load and inject properties into a Spring bean?

Spring Bean + Properties + Annotation configuration example Create a configuration class and define the properties bean in it as shown below. Create a spring bean class and inject properties into it using @Autowired and @Qualifier annotations. Create main class and run application.


1 Answers

It's possible in Spring 3.0 via Spring Expression Language:

<bean id="registryService" class="foo.MyRegistry"> ...properties set etc... </bean>  <bean id="MyClient" class="foo.MyClient">   <property name="endPoint" value="#{registryService.getEndPoint('bar')}"/> </bean> 
like image 79
ChssPly76 Avatar answered Sep 21 '22 18:09

ChssPly76