Grails bean into spring bean - spring

I'm trying to convert grails bean into spring bean
Resources.groovy
beans = {
testLoggingUtils(com.test.logging.LoggingUtils)
{
bean -> bean.factoryMethod = "getInstance"
}
trackLogging(testLoggingUtils: "getLogProcessorInstance")
}
I've converted above grails bean into
<bean id="testLoggingUtils" class="com.test.logging.LoggingUtils"
factory-method="getInstance"/>
<bean id="trackLogging" factory-bean="testLoggingUtils"
factory-method="getLogProcessorInstance"></bean>
This is the right way to do this? . Thanks for your help

Related

Spring Kotlin Bean DSL - register bean only if other bean is present?

I want to register bean (MyBean) only if another bean (anotherBeanThatShouldBePresent) is present in the context.
How I can achieve that?
bean {
MyBean(
anotherBeanThatShouldBePresent = ref()
)
}
You can use ObjectProvider to create bean depending on another bean
bean {
provider<OtherBeanOnWhichIDepend>().ifAvailable {
bean<MyCustomBean>()
}
}
With this code I will register MyCustomBean only if OtherBeanOnWhichIDepend bean is available

How can I create the spring bean after all other beans?

For example, I have 3 beans in my spring configuration: A, B, C. And I want to create bean B and C as usual. And than (when all others beans were created) I want to ask spring to create bean A.
Any suggestion ?
Thanks.
Spring framework triggers a ContextRefreshedEvent once the contexts has been fully refreshed and all the configured beans have been created.
You could try to create a listener to catch that event and initialise bean A.
#Component
public class ContextRefreshedEventListener implements
ApplicationListener<ContextRefreshedEvent> {
#Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
// Init your bean here
}
}
You should try #DependsOn adnotation
For example
<bean id="beanOne" class="ExampleBean" depends-on="manager,accountDao">
<property name="manager" ref="manager" />
</bean>
<bean id="manager" class="ManagerBean" />
<bean id="accountDao" class="x.y.jdbc.JdbcAccountDao" />
I know it's not really a bean ordering answer, but maybe you can achieve your goal with a #PostConstruct method that will be called just after a bean is constructed, dependencies are injected and all properties are set.
best nas
Easier way to do this would be using #Lazy annotation to your bean. This makes your bean do not get initialized eagerly during context initialization. In simple words,your bean will get created when you ask for it, not before.
#Bean
#Lazy
public A beanA() {
//some code here
}

Is it possible to inject beans using an XML file in Spring?

I am trying to inject a bean into an application using an XML file. The main function has
try(ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/spring/application.xml")) {
context.registerShutdownHook();
app.setResourceLoader(context);
app.run(args);
} catch (final Exception ex) {
ex.printStackTrace();
}
I also have a Person POJO and is set in the xml file.
The xml defination is as follows:
<context:annotation-config/>
<bean id="person" class="hello.service.Person" p:name="Ben" p:age="25" />
<bean class="hello.HelloBeanPostProcessor"/>
The link to my repo is:
https://bitbucket.org/rkc2015/gs-scheduling-tasks-complete
It is the default guide from Spring boot that does a scheduled task.
I'm trying to inject the Person POJO defined in the xml file into a scheduled task.
I am currently getting this error:
Error creating bean with name 'scheduledTasks': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private hello.service.Person
hello.service.ScheduledTasks.person; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type [hello.service.Person] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for
this dependency. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
Can anyone please help? I am new to Spring.
You can use #ImportResource annotation to import xml configurations.
Documentation link
#SpringBootApplication
#EnableScheduling
#ImportResource("/spring/application.xml")
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication app = new SpringApplication(Application.class);
app.run();
}
}
If this is through spring bean you should have used #component annotation for you bean definition or else i application.xml you should have defined scheduledTasks bean also and with it member variable of person so that both beans are created and can be autowired.

How to create a bean after ServletContext initialized in Spring Boot?

I have a bean, which implements ServletContextAware and BeanFactoryPostProcessor interfaces. I need this this bean register into the applicationContext after the ServletContext finished initialization, because I use some parameters in the servletContext to init this bean.
I am using the Spring Boot, the bean name is SpringBeanProcessorServletAware. I have add it into a configuration bean.
#Bean
public static SpringBeanProcessorServletAware springBeanProcessor() {
SpringBeanProcessorServletAware p = new SpringBeanProcessorServletAware();
return p;
}
My issue is that the bean is created before my container set servletContext to it. Then I can't get the parameters from the servletContext. How to control that the bean must be created after my servletContext has been created completely?

jersey-spring3: Injecting Jersey OAuth resource into Spring managed Bean

I am trying to insert a Jersey 2.7 resource withing a Spring managed bean. Specifically, I want to inject OAuth1Signature within a Spring bean like so:
#Component
public class OAuthManager {
#Inject
private OAuth1Signature oAuthSignature;
private void someMethod() {
String signature = oAuthSignature.generate(oauthRequest, params, secrets);
}
}
I have tried using instructions provided within the HK2 Spring integration document: HK2 Spring Integration. Following the document, I added this to my spring xml configuration:
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
<map>
<entry key="hk2">
<bean class="org.jvnet.hk2.spring.bridge.api.SpringScopeImpl" >
<property name="ServiceLocatorName" value="HK2ToSpringTest" />
</bean>
</entry>
</map>
</property>
</bean>
<bean id="org.glassfish.jersey.oauth1.signature.OAuth1Signature"
class="org.glassfish.jersey.oauth1.signature.OAuth1Signature"
scope="hk2"
lazy-init="true" />
However, I keep getting this exception when I start my webapp:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.glassfish.hk2.api.ServiceLocator] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:952)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:821)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:735)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:795)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:723)
OAuth1Signature documentation states that the ServiceLocator is supposed to be injected by HK2 framework which Jersey 2.7 uses. I am very confused on how I can get Spring to instantiate OAuth1Signature for me using the jersey-spring3 bridge since it does not seem to know where the Service locator should come from.
I have tried searching through StackOverflow and other Jersey message boards, but most of them deal with the opposite use case (injecting spring beans in a Jersey resource). Any help on this would be greatly appreciated !
I have recently done the development for OAuth in my project where I used Jersey 2.9.1 with Spring.
Below is what needs to be done to autowire the "OAuth1Signature's" instance in the Spring as we require hk2 to spring bridge to inject the hk2 services in the spring.
1.Define the custom hk2 scope
#Bean
public static CustomScopeConfigurer scopeConfigurer() {
Map<String, Object> scopeMap = new HashMap<String, Object>();
SpringScopeImpl hk2SpringScope = new SpringScopeImpl();
CustomScopeConfigurer customScopeConfigurer = new CustomScopeConfigurer();
hk2SpringScope.setServiceLocatorName("hk2SpringLocator");
scopeMap.put("hk2", hk2SpringScope);
customScopeConfigurer.setScopes(scopeMap);
return customScopeConfigurer;
}
2.Define the OAuth1Signature bean in "hk2" scope
#Bean(name = "oauth1Signature")
#Scope("hk2")
public OAuth1Signature getOAuth1Signature() {
ServiceLocator hk2ServiceLocator = ServiceLocatorFactory.getInstance()
.find("hk2SpringLocator");
OAuth1Signature oAuth1Signature = new OAuth1Signature(hk2ServiceLocator);
return oAuth1Signature;
}
3.After you are done with above 2 steps, you are ready to the autowire the "OAuth1Signature".
#Autowired
private OAuth1Signature oAuth1Signature;
Cheers

Resources