How can I get Spring to instantiate a bean that does not have a no-argument constructor? I'm using java-config (not xml-config). It seems to work using XML -but shouldn't I be able to do the same thing with annotations somehow?
Straight from the tutorial, the following example is the equivalent in xml-config:
<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg index="0" value="7500000"/>
<constructor-arg index="1" value="42"/>
</bean>
It also mentions the use of #ConstructorProperties annotation, which I've tried to use -but I can't get it to work. I keep getting a BeanInstantiationException.
#Configuration
public class MyConfiguration {
#Bean
public ExampleBean exampleBean() {
return new ExampleBean(7500000, 42);
}
}
Or:
#Configuration
#PropertySource(value = { "my.properties" })
public class MyConfiguration {
#Value("{prop.value1}")
private int value1;
#Value("{prop.value2}")
private int value2;
#Bean
public ExampleBean exampleBean() {
return new ExampleBean(value1, value2);
}
}
also from the link below
http://docs.oracle.com/javase/6/docs/api/java/beans/ConstructorProperties.html
what i understood is, #ConstructorProperties annotation is not to be used as a replacement for your xml-config.
Can you use #Autowired with #Qualifier, like in another SO Article?
You can use #Autowired or #Inject
Related
i am really confused with spring annotations.
where to use # Autowired, where class is # Bean or # Component,
i understand we cannot use
Example example=new Example("String");
in Spring
but how alone
#Autowired
Example example;
will solve the purpose?
what about Example Constructor ,how spring will provide String value to Example Constructor?
i went through one of the article but it does not make much sense to me.
it would be great if some one can give me just brief and simple explanation.
Spring doesn't say you can't do Example example = new Example("String"); That is still perfectly legal if Example does not need to be a singleton bean. Where #Autowired and #Bean come into play is when you want to instantiate a class as a singleton. In Spring, any bean you annotate with #Service, #Component or #Repository would get automatically registered as a singleton bean as long as your component scanning is setup correctly. The option of using #Bean allows you to define these singletons without annotating the classes explicitly. Instead you would create a class, annotate it with #Configuration and within that class, define one or more #Bean definitions.
So instead of
#Component
public class MyService {
public MyService() {}
}
You could have
public class MyService {
public MyService() {}
}
#Configuration
public class Application {
#Bean
public MyService myService() {
return new MyService();
}
#Autowired
#Bean
public MyOtherService myOtherService(MyService myService) {
return new MyOtherService();
}
}
The trade-off is having your beans defined in one place vs annotating individual classes. I typically use both depending on what I need.
You will first define a bean of type example:
<beans>
<bean name="example" class="Example">
<constructor-arg value="String">
</bean>
</beans>
or in Java code as:
#Bean
public Example example() {
return new Example("String");
}
Now when you use #Autowired the spring container will inject the bean created above into the parent bean.
Default constructor + #Component - Annotation is enough to get #Autowired work:
#Component
public class Example {
public Example(){
this.str = "string";
}
}
You should never instantiate a concrete implementation via #Bean declaration. Always do something like this:
public interface MyApiInterface{
void doSomeOperation();
}
#Component
public class MyApiV1 implements MyApiInterface {
public void doSomeOperation() {...}
}
And now you can use it in your code:
#Autowired
private MyApiInterface _api; // spring will AUTOmaticaly find the implementation
I want to declare and inject a bean through annotations. It was previously done through XML, but I need to apply on a Spring Boot project.
Here is the source xml
<oauth:resource-details-service id="rds">
<oauth:resource
id="oauth1"
key="${key}"
secret="${secret}"
request-token-url="${token}"
user-authorization-url="${user-auth}"
access-token-url="${accesstokenurl}">
</oauth:resource>
</oauth:resource-details-service>
The bean was later used like this
<bean class="org.springframework.security.oauth.consumer.client.OAuthRestTemplate">
<constructor-arg ref="oauth1"/>
</bean>
The only way I found is through direct instantiation
BaseProtectedResourceDetails resourceDetails = new BaseProtectedResourceDetails();
resourceDetails.set...
resourceDetails.set...
OAuthRestTemplate restTemplate = new OAuthRestTemplate(resourceDetails);
What would be the proper way to do this?
you can use #Bean annotation in your main class for example:
#SpringBootApplication
public class Application{
#Bean
public OAuthRestTemplate getAuth(){
BaseProtectedResourceDetails resourceDetails = new BaseProtectedResourceDetails();
resourceDetails.set...
resourceDetails.set...
return new OAuthRestTemplate(resourceDetails);
}
}
and after use #Autowired to inject the object
#Autowired
private OAuthRestTemplate oAuthRestTemplate;
I am not sure you are searching for this explanation. But if I understand you question then following information may help you.
For Sample configuration class you can see this example.
package com.tutorialspoint;
import org.springframework.context.annotation.*;
#Configuration
public class TextEditorConfig {
#Bean
public TextEditor textEditor(){
return new TextEditor( spellChecker() );
}
#Bean
public SpellChecker spellChecker(){
return new SpellChecker( );
}
}
And for registering configuration class, you can see this SO answer.
See this for #Service, #Component, #Repository, #Controller, #Autowired related example.
Java - Spring
I have spring factory bean creation in .xml
<bean id="concurrentHashMapFactory" class="com.abc.HashMapFactory.ConcurrentHashMapFactory"/>
<bean id="idCorpMap" factory-bean="concurrentHashMapFactory" factory-method="createIdCorpMapInstance"/>
but i want to convert above .xml statement into equivalent using annotation any help ?
Roughly like this (I didn't test it)..
#Configuration
public class Config {
#Bean(name = "concurrentHashMapFactory")
public ConcurrentHashMapFactory createConcurrentHashMapFactory() {
return new ConcurrentHashMapFactory();
}
#Bean(name = "idCorpMap")
public IdCorpMapType createIdCorpMap(ConcurrentHashMapFactory factory) {
return factory.createIdCorpMapInstance();
}
}
What is the equivalent of
<bean id="myClass" class="com.xxx.MyClass" factory-method="aspectOf" />
when using a Spring 4 #Bean-annotated method?
There is no annotation for the factory method, but you can use the #Configuration and #Bean annotations
#Configuration
public class MyClass {
#Bean
public MyClass myObject() {
return MyStaticFactory.getObject();
}
}
MyStaticFactory does not require any Spring annotations.
Use #Configurable with <context:spring-configured>
How would I specify an anonymous inner bean in a named Spring Service?
#Service("myNamedService")
public class myNamedServiceClass {
private InnerBeanType innerBean;
#Autowired
public void setInnerBean(InnerBeanType innerBean) {
this.innerBean = innerBean;
}
}
I'm basically trying to achieve the equivalent of the following Spring XML wiring:
<bean name="myNamedService" class="somePackage.myNamedServiceClass">
<property name="innerBean">
<bean class="somePackage.InnerBeanType"/>
</property>
</bean>
Equivalent using pure annotations is I think not possible. You can use #Configuration though if the purpose is to not expose innerBean as a visible bean this way:
#Bean
public MyNamedServiceBean myNamedServiceBean(){
MyNamedServiceClass myNamedServiceBean = new MyNamedServiceClass();
myNamedServiceBean.setInnerBean(new InnerBeanType());
return myNamedServiceBean;
}