Autowired beans are null in CustomRepositoryImpl [duplicate] - java

This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 9 years ago.
I'm just starting out with Spring Data and I'm trying to add a custom method to my repositories which requires another bean (which is preferably only created once (i.e. singleton))
The bean is declared in the root-context.xml like so
<bean class="org...CachedQueryTemplateFactory" />
With the proper namespace of course. I then try to inject this bean into a CustomRepositoryImpl using #Autowired
#Getter
#Setter
#Component
public class StudyRepositoryImpl implements StudyRepositoryCustom {
#PersistenceContext private EntityManager d_em;
#Autowired private QueryTemplateFactory queryTemplateFactory;
#Override
public List<Study> findStudies(
UUID indication,
List<UUID> variables,
List<UUID> treatments) {
QueryTemplate template = this.queryTemplateFactory.buildQueryTemplate("...");
...
}
}
However when running the code I get NullPointerException. When doing the wiring in a #Controller and then passing the reference to the repository it works, but I don't want to DI to happen in the controller. So why is the QueryTemplateFactory null in the StudyRepositoryImpl but not for the #Controller and how can I fix this?
Full code is available on GitHub https://github.com/joelkuiper/trialverse/tree/feature/injectQueryTemplate
Thanks in advance!

You probably just need to add either :
<context:component-scan base-package="packagewithservices"/>
OR
<context:annotation-config/>
Either of these register a AutowiredAnnotationBeanPostProcessor responsible for wiring in the #Autowired fields. The javadoc that I have linked to has more details.

Related

What is the best practice to solve the issue "My bean is null after I new a object" [duplicate]

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.

Spring Boot accessing dao service from custom class [duplicate]

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.

Preferable way to use a bean in self-initialized objects in Spring

I've been working around Java and Spring(Batch, Boot), and have a question.
I created beans by Spring for generating a service class. I bind it with #Autowired annotation like this:
#Component
public class MyTaskRunner {
#Autowired
private MyService myService;
public void run() {
List<SomeObject> someObjects = myService.getSomeObjects();
// Do some tasks
}
}
Here, I also want to use such a bean in SomeObject which are deserialized from a database(meaning, not from Spring). I've looked for solutions here and am going to try them, but most of them seem elaborate, just for injecting a bean.
My question is: Is it so unusual usage of bean that it needs some work?
Thank you in advance! Any comments would be appreciated.

Why is this DAO in spring returning a null pointer [duplicate]

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.

Spring - autowire a class that have a constructor [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Anyway to #Autowire a bean that requires constructor arguments?
In my controller I want to use #Autowired to inject a class using the method / constructor autowiring. for example using:
#Autowired
private InjectedClass injectedClass;
My problem is that the injected class injectedClass have a constructor, and I need to pass a variable to the constructor from the controller. How can I pass values to the constructors?
If you are using annotations you can apply #Autowired annotation to MyClass's constructor, which will auto wire beans you are passing to MyClass's special constructor. Consider following e.g.
public class MovieRecommender {
#Autowired
private MovieCatalog movieCatalog;
private CustomerPreferenceDao customerPreferenceDao;
#Autowired
public MovieRecommender(CustomerPreferenceDao customerPreferenceDao) {
this.customerPreferenceDao = customerPreferenceDao;
}
// ...
}
You can either mark private data members with #Resource(name = "x") annotation OR wire them using constructor injection in the application context XML.
Annotations and XML configuration can be mixed in Spring. It need not be all or nothing.
<bean id="myClass" class="foo.bar.MyClass">
<constructor-arg ref="yourArgRefHere"/>
</bean>

Categories