I am trying to use an autowired reference from main class and am facing :
Cannot make a static reference to the non-static field
zipCodeLookupService.
This is obvious. But I want to know how to handle this situation. What is the correct way of autowiring when main class is involved. My code will be as below -
Interface class
package com.example.services;
public interface IZipCodeLookup {
String retriveCityForZip(String zipCode);
}
Service Class
package com.example.services;
import org.springframework.stereotype.Service;
#Service
public class ZipCodeLookupService implements IZipCodeLookup {
#Override
public String retriveCityForZip(String zipCode) {
//below is mock code. actual code does a db lookup using a DAO.
if(zipCode=="94123") return "San Francisco";
return "not found in DB";
}
}
here is the main class that requires the service class
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.example.services.IZipCodeLookup;
#SpringBootApplication
public class AutowireWithMainClassApplication {
#Autowired
IZipCodeLookup zipCodeLookupService;
public static void main(String[] args) {
SpringApplication.run(AutowireWithMainClassApplication.class, args);
String city;
//this will not work, compilation error
//Cannot make a static reference to the non-static field zipCodeLookupService
city=zipCodeLookupService.retriveCityForZip(args[0]);
System.out.println("city for zipcode " + args[0] + " is " +city);
}
}
Could someone suggest - how or what is the correct way of using autowiring when main class is involved.
(As making the Autowired reference as static does not work anyway)
in AutowireWithMainClassApplication class, changing to -
#Autowired
static IZipCodeLookup zipCodeLookupService;
throws
Exception in thread "main"
java.lang.NullPointerException
You can do one of the following:
Use the #Autowired object in a #PostConstruct method, which is executed after dependency injection is done, as davidxxx explained above
Use Spring's getBean() in your main() to explicitly ask Spring framework to return the object after the injection completes:
public static void main(String[] args) {
...
ConfigurableApplicationContext appContext = SpringApplication.run(StartApplication.class, args);
IZipCodeLookup service = appContext.getBean(IZipCodeLookup.class);
...
}
Use Spring's CommandLineRunner component (runs right after main), which will be responsible on autowiring your object:
#Component
public class MyRunner implements CommandLineRunner {
#Autowired
private IZipCodeLookup service;
#Override
public void run(String... args) throws Exception {
...
service.doSomething();
...
}
}
Implement Spring's ApplicationRunner's run method in your main:
#SpringBootApplication
public class StartApplication implements ApplicationRunner {
#Autowired
private IZipCodeLookup service;
public static void main(String[] args) {
ConfigurableApplicationContext appContext = SpringApplication.run(StartApplication.class, args);
}
#Override
public void run(ApplicationArguments args) throws Exception {
...
service.doSomething();
...
}
}
A class annotated with a #SpringBootApplication annotation is not a classic bean.It creates the Spring context from a static method.
But autowired dependencies cannot be static.
That's why this statement :
city=zipCodeLookupService.retriveCityForZip(args[0]);
doesn't throw a Spring exception but a classic NullPointerException as you declare zipCodeLookupService as a static field.
In your case, as workaround, you could move the processing that uses the Spring bean in a instance method annotated with javax.annotation.PostConstruct method inside your main class and store the arguments passed to the main() method in a field in order to be able to use it later :
private static String[] args;
#Autowired
IZipCodeLookup zipCodeLookupService;
public static void main(String[] args) {
AutowireWithMainClassApplication.args = args;
SpringApplication.run(AutowireWithMainClassApplication.class, args);
}
#PostConstruct
public void init() {
String city=zipCodeLookupService.retriveCityForZip(args[0]);
System.out.println("city for zipcode " + args[0] + " is " +city);
}
To answer to your comment, you should note several things about #PostConstruct
1) It is not an annotation specific to Spring. So, the official documentation may discuss about things more general than Spring or specific but different things such as EJB (it was originally introduced for them).
2) The first sentence of the javadoc summarizes the general expected behavior.
The PostConstruct annotation is used on a method that needs to be
executed after dependency injection is done to perform any
initialization.
But this sentence
"executed after dependency injection is done"
means indeed :
"executed after all dependency injections are done"
We talk about dependency injection in general, not about each dependency injection.
So, yes stick you to that.
Applying it to your case should make things clearer.
The AutowireWithMainClassApplication class is considered as a Spring bean as #SpringBootApplication is annotated with #Configuration that is itself annotated with #Component.
And as any Spring bean, it may declare dependency injection.
That is a dependency injection :
#Autowired
IZipCodeLookup zipCodeLookupService;
But you could of course declare as many dependency injections that you want to :
#Autowired
IZipCodeLookup zipCodeLookupService;
#Autowired
OtherClass otherClass;
...
So only as all dependencies are effectively injected, the PostConstructwill be invoked one and once.
Related
I am using Alfresco Process Services and have created a created a spring boot project for custom logic like TaskListeners and Delegations. I am creating the jar file from this maven project and copying it into webapps/activiti-app/WEB-INF/lib folder.
I have a simple TaskListener as below which is getting called on Task start. But the #Autowired variables are always null.
package com.activiti.extension.bean;
#Component("myTaskListener")
public class MyTaskListener implements TaskListener {
#Autowired
UserService userService;
#Override
public void notify(DelegateTask task) {
logger.info("userService: " +userService); // Always prints null
}
Finally I was able to make it work. I was putting the task listener in the class field of the Task properties with full package name. Now I am putting Delegate expression like ${myTaskListener} and it worked...
Thank you all for your time and help
This is because your your MyTaskListener is annotated as #Component or at least being ignored by spring during init. for auto-wiring capabilities spring requires this annotation (or similar to this) under the provided #ComponentScan packages to consider the class as a bean otherwise it will take as a normal java class and hence the #autowired is of no use in your case.
This below code is worked for me
#Component
public class MyTaskListener implements TaskListener {
public static UserService getUserServiceObject() {
return SpringApplicationContextHolder.getApplicationContext().getBean(UserService.class);
}
#Override
public void notify(DelegateTask delegateTask) {
//UserService Object, It is not null now
getUserServiceObject();
}
}
#Component
public class SpringApplicationContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
There is also one more way to get to your custom service "UserService" using Alfresco Spring Application context.
First access ServiceRegistry (registry used for accessing Alfresco Services but also any other custom service):
ServiceRegistry serviceRegistry = (ServiceRegistry) Context.getProcessEngineConfiguration().getBeans().get(ActivitiConstants.SERVICE_REGISTRY_BEAN_KEY);
Then get custom service UserService:
QName qname = QName.createQName("UserService");
UserService userService = (UserService) serviceRegistry.getService(qname);
This is driving me nuts. I have the following files, it is a very simple setup.
public class MainApp {
public static void main(String[] args) {
//read the spring config java class
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("Config.class");
//System.out.println("Bean names: " + Arrays.toString(context.getBeanNamesForType(AccountDAO.class)));
//get the bean from spring container
AccountDAO accountDAO = context.getBean("accountDAO", AccountDAO.class);
//call the business method
accountDAO.addAccount();
//close the spring context
context.close();
}
}
Config.java:
#Configuration
#ComponentScan("com.aop")
#EnableAspectJAutoProxy
public class Config {
}
LoggingAspectDemo.java:
#Aspect
#Component
public class LoggingAspectDemo {
//this is where we add all our related advices for the logging
//let's start with an #Before advice
#Before("execution(public void addAccount())")
public void beforeAddAccountAdvice() {
System.out.println("\n=======>>>> Executing #Before advice on method addAccount() <<<<========");
}
}
AccountDAO.java
#Component
public class AccountDAO {
public void addAccount() {
System.out.println(getClass() + ": Doing my Db work: Adding an account");
}
}
Everytime I run the MainApp.java, I get:
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'accountDAO' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:687)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1207)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
All the files are under "com.aop" package so #ComponentScan should be scanning all the components. It looks simple enough but I can't get my hands around the problem, can anyone help me where I am going wrong?
You're invoking the constructor of AnnotationConfigApplicationContext with "Config.class" as String argument, but this constructor is actually for invoking with base packages i.e. the argument must be a package name.
Since you want to use it with the Configuration class, use the constructor which accepts Class instance instead i.e.
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
I'm trying to understand Spring proxy mechanism and I have problem with one thing.
I have Interface:
public interface MyInterface{
void myMethod();
}
and implementing class:
#Component
public class MyBean implements MyInterface{
#Override
public void myMethod(){
//do something
}
}
Now I create Aspect, for example:
#Aspect
#Component
public class LogAspect {
#Before("execution(public * *(..))")
public void logBefore() {
System.out.println("Before aspect");
}
}
And I have simple starter class:
#Configuration
#ComponentScan
#EnableAspectJAutoProxy
public class SpringAopApplication {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(
SpringAopApplication.class);
MyBean bean = ctx.getBean(MyBean.class);
// MyInterface bean = ctx.getBean(MyInterface.class); //works
bean.myMethod();
ctx.close();
}
}
According to the Spring docs we can read:
If the target object to be proxied implements at least one interface
then a JDK dynamic proxy will be used. All of the interfaces
implemented by the target type will be proxied. If the target object
does not implement any interfaces then a CGLIB proxy will be created.
But I got an error No qualifying bean of type [MyBean] is defined. It works only when I enable CGLib proxying by #EnableAspectJAutoProxy(proxyTargetClass = true).
Can someone explain what I am missing here? Why MyBean is not discovered when using AOP? ctx.getBean(MyInterface.class) works, but I can't imagine the situation with many implementations of such interface.
The target object to be proxied (MyBean) implements at least one interface (MyInterface), so a JDK proxy is used.
This proxy implements MyInterface, but is NOT an instance of MyBean.
Thats why
MyInterface bean = ctx.getBean(MyInterface.class);
works and
MyBean bean = ctx.getBean(MyBean.class);
not.
CGLib proxies are created by subclassing the target object, so the bean created is a subclass of MyBean and implements MyInterface.
In this case also
MyBean bean = ctx.getBean(MyBean.class);
works.
...but I can't imagine the situation with many implementations of such interface.
The only reason for MyInterface could be, to allow spring to create a JDK proxy, so there is no need to have many implementations.
Because if you check up your bean class you'll find com.sun.proxy.$Proxy21 (or something similar) instead, which wraps your method. They are incompatible types even they have the same interface.
For example:
public interface AnInterface {
void func();
}
public class Bb implements AnInterface{
#Override
public void func() {
System.out.println("bb");
}
}
public class Cc implements AnInterface{
#Override
public void func() {
System.out.println("cc");
}
}
So when you call
public static void main(String[] args) {
Bb b = new Bb();
Cc c=b; // Error
AnInterface c=b; // Ok
}
I am trying to save data on gemfire using crud repository. I have created one operation class to call save method of repository but at autowired instance I am getting null pointer exception. Below is my code:
public interface GeodeRepository extends CrudRepository<KeyValueBean, String> {
#Override
public KeyValueBean findOne(String name);
#Override
public <S extends KeyValueBean> Iterable<S> save(Iterable<S> entities);
}
#EnableGemfireRepositories(basePackageClasses = GeodeRepository.class)
#EnableAutoConfiguration
#Configuration
public class Operations {
#Autowired
private GeodeRepository repository;
public void saveKeyValueData(KeyValueBean keyValueBean) {
System.out.println("Repository is : " + repository);
repository.save(Arrays.asList(keyValueBean)); // <--- i am getting
// repository as null so
// getting null pointer
// exception
}
}
When we #Autowired any class make sure, you have declared that class as a #Component.
for example:
#Component
public class Operations {
#Autowired
private GeodeRepository repository;
public void saveKeyValueData(KeyValueBean keyValueBean) {
System.out.println("Repository is : " + repository);
repository.save(Arrays.asList(keyValueBean));
}
}
and try using #Autowired to Operation class to your class
in which class your are calling your saveKeyValueData() method.
So, what is not apparent from your example is how you "bootstrap" your application and it's features (e.g. Repositories) into action.
It is not simply enough to add the Spring #Configuration, Spring Boot's #EnableAutoConfiguration and SD GemFire's #EnableGemfireRepositories annotations and expect everything to be auto-configured and wired up successfully. I.e. you need a bootstrapping mechanism, like Spring Boot, especially if you are using the #EnableAutoConfiguration annotation.
For example...
import org.springframework.boot.SpringApplication;
...
class MyApplication {
public static void main(String[] args) {
SpringApplication.run(Operations.class, args);
}
}
Now, you could remove the #EnableAutoConfiguration from your Operations class and add the #SpringBootApplication to the MyApplication class, like so...
#SpringBootApplication
class MyApplication {
...
}
#SpringBootAppliation combines together Spring's #Configuration with Spring Boot's #EnableAutoConfiguration, along with many other useful meta-annotations, like Spring's #ComponentScan, enabling all sorts of magic to happen.
But, if you are not using Spring Boot, you can always bootstrap you application with the AnnotationConfigApplicationContext, like so..
class MyApplication
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext =
new AnnotationConfigApplicationContext(Operations.class);
applicationContext.registerShutdownHook();
}
}
This is essentially what the Spring Boot, SpringApplication class does for you anyway.
If you are developing a Web application, then of course you can specify the type of ApplicationContext created since you are using Java config, for instance. See here for more details.
Hope this helps!
Cheers,
John
Java 8 added a new feature by which we can provide method implementation in interfaces.
Is there any way in Spring 4 by which we can inject beans in the interface which can be used inside the method body?
Below is the sample code
public interface TestWiring{
#Autowired
public Service service;// this is not possible as it would be static.
//Is there any way I can inject any service bean which can be used inside testWiringMethod.
default void testWiringMethod(){
// Call method of service
service.testService();
}
}
This is a bit tricky but it works if you need the dependency inside the interface for whatever requirement.
The idea would be to declare a method that will force the implemented class to provide that dependency you want to autowire.
The bad side of this approach is that if you want to provide too many dependencies the code won't be pretty since you will need one getter for each dependency.
public interface TestWiring {
public Service getService();
default void testWiringMethod(){
getService().testService();
}
}
public class TestClass implements TestWiring {
#Autowire private Service service;
#Override
public Service getService() {
return service;
}
}
You can created Class utils of application context and use it everywhere even not bean class .
you can have code somethins this :
public class ApplicationContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
#Override
public void setApplicationContext(ApplicationContext context) {
ApplicationContextUtil.applicationContext = context;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
}
and add this to your spring configuration
<bean class="com.example.ApplicationContextUtil" id="applicationContextUtil"/>
now simple to use when you need :
ApplicationContextUtil.getApplicationContext().getBean(SampleBean.class)
this word in web and simple spring app.