I have a Util class with static methods. Inside my Util class, I want to use spring beans so I included them in my util class. As far as I know it\'s not a good practice to
This worked for me.
Define your bean using xml configuration (old school):
<bean id="someBean1" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"><value>${db.driver}</value></property>
<property name="url"><value>${db.url}</value></property>
<property name="username"><value>${db.username_seg}</value></property>
<property name="password"><value>${db.password_seg}</value></property>
</bean>
Or define it with java instead xml (new school)
@Bean(name = "someBean2")
public MySpringComponent loadSomeSpringComponent() {
MySpringComponent bean = new MySpringComponent();
bean.setSomeProperty("1.0.2");
return bean;
}
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
public class TestUtils {
public static void getBeansFromSpringContext() {
WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
//for spring boot apps
//ApplicationContext context = SpringApplication.run(Application.class, args)
DataSource datasource = (DataSource)context.getBean("someBean1");
MySpringComponent springBean = (MySpringComponent)context.getBean("someBean2");
}
}
HTH
This is how I injected from spring for a static field.
<bean id="..." class="...">
<property name="fieldToBeInjected">
<util:constant static-field="CONSTANT_FIELD" />
</property>
</bean>
Maybe this will help you, as well.