This question already has answers here:
Accessing spring beans in static method
(7 answers)
Closed 2 years ago.
I would like to create a helper class, but it just failed..
The error : java.lang.NullPointerException: null
When i do this without making a static class (with autowired) it works without problem. But it's a helper class, i think the static class is the better thing.
Thanks for help
Helper.java
public final class UrlHelper {
#Autowired
private static Environment bean;
public static String method(String projet) {
return "titi"+ bean.getProperty("property.name");
}
}
And in my service, i use it like this :
String list = getRequest.getHTTPRequest(UrlHelper.method(projet));
In Spring, the #Autowired annotation allows you to resolve and inject beans into other beans. In your case, the UrlHelper class is not a bean and therefore, your Environment is not injected (stays null), hence the error. You have two options:
Make the UrlHelper a bean using #Component, #Service, etc. This will make your class non-static.
Keep the UrlHelper static, and pass the Environment as parameter. This, I believe, is the more correct approach. The Environment can be injected in the class calling the static method.
Related
This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 1 year ago.
I have a bean used in MyApp, but when I have MyApp app = new MyApp(), then carIF is null. What is the best practice to solve this issue? I have tried to make MyApp as a bean as well by adding #Component, so I don't need to do 'new MyApp()', but it turns out I need to keep making a java class as bean in my java classes calling workflow, which I don't think it is a right approach. How to solve the issue like this?
public class MyApp() {
#Autowired
private CarIF carIF;
When you instantiate the class on your own (MyApp()) you are not taking advantage of Spring-managed Beans and Spring Dependency Injection features. When you do it like that you can't expect Spring to inject a CarIF instance in your newly created MyApp instance.
As you mentioned, you should make MyApp a Spring-managed Bean by, for example, annotate it with #Component as follows:
#Component
public class MyApp() {
#Autowired
private CarIF carIF;
}
This will generally work, but it really depends on your project setup and if you are following a usual Spring project structure.
This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Role of new keyword in Spring Framework
(1 answer)
Closed 3 years ago.
I am trouble with accessing my service to save data in a class.
I have a class and wish to use my defined service that works well in my RestController by am struggling to access it in custom class.
I wish to do something like the following new MessageProcessor.processMessage(message) --> this should access service and save the data to database.
#Controller
public class MessageProcessor {
#Autowired
private IOTService iotService;
public MessageProcessor() {
}
public void processMessage(String message) {
iotService.addMessage(message);
}
}
It is being called like this in a random class.
The Autowired annotion is not working as i expected.
new MessageProcessor().processMessage("test");
I am new to Spring so any suggestions would be appreciated
First of all, you need to understand how the framework work. I am giving an example, may be it clears some of your doubts and logic.
The autowiring works in a way like, you have to follow a standard :
Make a domain class (Domain.class).
Make a controller (DomainController.class)(if there is need), mark it with annotation #Controller.
Make a service class,(DomainService.class), mark it with annotation #Service
In this way, you can use autowiring concept. If you want to use your service class method outside this class hierarchy, you have create its new instance with new keyword i.e. new DomainService()
The thing to be noted here autowiring works within a specific model not everywhere.
This question already has answers here:
Spring: How to inject a value to static field?
(5 answers)
Closed 3 years ago.
environment properties are there in application.properties
application.properties
app.mail.allowedDomains=gmail
in class
#Autowired
private Environment env;
#Value("${app.mail.allowedDomains}")
private static String allowedDomainsForMail;
#Value("${app.mail.allowedDomains:nothing}")
private static String allowedDomainsForMail2;
public void printProperties() {
System.out.println("Inside impl");
System.out.println("#Value:\t" + allowedDomainsForMail);
System.out.println("#Value:\t" + allowedDomainsForMail2);
System.out.println("Env:\t" + env.getProperty("app.mail.allowedDomains"));
}
Output
Inside impl
#Value: null
#Value: null
Env: gmail
It is not even setting "nothing"(default value if not found) in 2nd scenario. But from env it's printing
I even tried with #ConfigurationProperties in main class of package.
No success.
Is value fetched from env file on each hit or on app load only it will load?
Value from org.springframework.beans.factory.annotation.Value
Spring does not allow inject into a static field. Overall it's considered not a good practice. Below a few links which might help you to understand why.
link#1
link#2
Remove static and the injection should happen, since the env Environment was injected.
The Spring doesn't support static field injection. Also #Value annotation is also not the best practice.
The best way is to use #ConfigurationProperties annotation and bind it with application properties. It will help you to mock Configration Bean in Unit tests, instead of use reflection for #Value injection
This question already has answers here:
How to add bean instance at runtime in spring WebApplicationContext?
(3 answers)
Closed 3 years ago.
I'm developing a framework in Spring boot, that is used by some applications. In some point at runtime, the application supply me (the framework)
an instance of class A, that I want to aspect (using spring) its func method.
The problem is, that I am not the one who construct this instace so I can't create it by applicationContext.getBean(A.class).
Is there a way to give Spring this instance and tell it to make it (or proxy it with) a bean?
public interface A {
void func(int i);
}
Aspect:
#Aspect
public class AspectClass {
#Around("execution(*com.A.func(..))")
public void funcAspect(ProceedingJoinPoint joinPoint) throws Throwable {
....
}
}
I expect it to be something like: A bean = applicationContext.makeBean(instanceOfA)
EDIT: I can't control the construction of A, I'm not the one who construct it, and I just get its existing instance and want to aspect its func method, from now on.
Are you aware of #Bean annotation in Java #Configuration class? this is the 3rd and popular way of creating beans and that's exactly for the moment, when you don't want your Spring container to instantiate default beans from the candidate classes, but rather create your custom object (in the #Bean method), make any adjustments to that object (before you return it) and finally return that instance. Spring will automatically register that (your custom object) object as a bean in its application context.
This question already has answers here:
spring junit testing
(3 answers)
Closed 7 years ago.
Trying to call a very simple method from a junit test.
I have an interface and class:
public interface CacheSampleDao {
String sample(String a);
}
and
public class CacheSampleImpl implements CacheSampleDao {
public String sample(String a) {
return "1";
}
}
This class is also a bean in my context.xml
<bean class="com.premierinc.datascience.repo.CacheSampleImpl"/>
and a test
#Test
public class CacheSampleTest extends AbstractTest {
#Autowired CacheSampleDaoImpl cacheSampleDaoImpl;
#Test
public void cacheTest() {
String a = cacheSampleDaoImpl.sample("A");
}
}
Why would this test be giving a Null Pointer Exception? Is there some something else configuration related that needs to be done for this or some other step that I am missing?
Using an interface is fine.
The issue you have is because you #Autowired statement is:
#Autowired CacheSampleDaoImpl cacheSampleDaoImpl;
But where is your DaoImpl? The bean you have created is a CacheSampleImpl, which implements the CacheSampleDao interface, not the DaoImpl.
Also, the property should be named according to the bean you created, you have no bean named cacheSampleDaoImpl or a bean of type CacheSampleDaoImpl for the autowiring to successfully resolved.
Based on the code you have shown (which excludes the CacheSampleDaoImpl) I believe what you want is this:
#Autowired CacheSampleDao cacheSampleImpl;
There is a good post on how to do this here:
Spring autowire interface
For integration tests with spring you should care about inserting spring context to the test, in other case there is nothing that will care about building and injecting of the beans, that actually happen in your test.
As a solution you can annotate your test with this annotations: #ContextConfiguration and #RunWith like this:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("/your-spring-context.xml")
You can rad more about testing in spring in spring referents documentation.