Spring Boot Autowired failed - null - spring-boot

I have 3 classes which are found in different packages in a spring boot application as follows:
Why does #Autowired work in certain classes only?Anything I am doing wrong?
#Configuration
public class Configurations{
#Autowired
Prop prop; //works fine
#Bean
//other bean definitions
}
#Component
public class Prop{
public void method(){};
}
public class User{
#Autowired
Prop prop; //does not work, null
public void doWork(){
prop.method();
}
}
I have also tried the #PostConstruct, but same result
public class User{
#Autowired
Prop prop; //does not work, null
#PostConstruct
public void doWork(){
prop.method();
}
}

The #Autowired annotation works only if Spring detects that the class itself should be a Spring bean.
In your first example you annotated Configurations with the #Configuration annotation. Your User class on the other hand does not have an annotation indicating that it should be a Spring bean.
There are various annotations (with different meanings) to make your class being picked up by the Spring container, some examples are #Service, #Component, #Controller, #Configuration, ... . However, this only works if your class is in a package that is being scanned by the Spring container. With Spring boot, the easiest way to guarantee that is by putting your User class in a (sub)package of your main class (the class annotated with #SpringBootApplication).
You can also manually create your bean by writing the following method in your Configurations:
#Bean
public User user() {
return new User();
}
In this case you don't have to annotate your User class, nor do you have to make sure that it is in a package that is being scanned.

Related

why #Autowired work without #Component when inside #Configuration

I am configuring the shiro-spring-starter.
#Configuration
public class ShiroConfig {
#Bean
public Realm realm() {
return new UserRealm();
}
}
\\Without #Component
public class UserRealm extends AuthorizingRealm {
#Autowired
private UserMapper userMapper;
}
UserRealm was create using "new UserRealm()",without #Component.
why the #Autowired work?
In your code, the #Component annotation is not required because you've created the UserRealm object as a spring bean in the ShiroConfig class. Since it's a spring bean, spring will manage the object and perform the dependency injections specified by the #Autowired annotation.
If you didn't create the UserRealm object as a spring bean in the ShiroConfig class, you would then need the #Component annotation on the UserRealm class. The #Component annotation would cause spring to automatically create an instance of the UserRealm class as a spring bean, assuming component scanning is enabled.
So you either don't use a #Component annotation and manually create spring beans in your configuration class, or use the #Component annotation and let spring automatically create the spring bean. The result is the same.

what is the difference between #Bean annotation and #Component annotation at Spring?

It might be a very simple question for you.But I read lots of documents and I am totally confused.We can use #Component instead of #Bean or #Bean instead of #Component(as well as #Repository #Service #Controller) ?
Cheers
Component
#Component also for #Service and #Repository are used to auto-detect and auto-configure beans using classpath scanning.
As long as these classes are in under our base package or Spring is aware of another package to scan, a new bean will be created for each of these classes
Bean and Component are mapped as one to one i.e one bean per Class.
These annotations (#Component, #Service, #Repository) are Class level annotations.
Example:
Lets Say we have a UserService Class which contains all methods for User Operation.
#Service
public class UserService {
#Autowired
private UserRepository userRepository;
#Override
public User findByUsername( String username ) throws UsernameNotFoundException {
User u = userRepository.findByUsername( username );
return u;
}
public List<User> findAll() throws AccessDeniedException {
List<User> result = userRepository.findAll();
return result;
}
}
Spring will create a Bean for UserService and we can use this at multiple location/classes.
#Bean
#Bean is used to declare a single bean, rather than letting Spring do it automatically as in case of Component.
It decouples the declaration of the bean from the class definition, and lets you create and configure beans exactly how you choose.
#Bean are used at method level and can be configured as required
eg:
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Bean
public SpringTemplateEngine springTemplateEngine()
{
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.addTemplateResolver(htmlTemplateResolver());
return templateEngine;
}
#Bean
public SpringResourceTemplateResolver htmlTemplateResolver()
{
SpringResourceTemplateResolver emailTemplateResolver = new SpringResourceTemplateResolver();
emailTemplateResolver.setPrefix("classpath:/static/template/");
emailTemplateResolver.setSuffix(".html");
emailTemplateResolver.setTemplateMode("HTML");
emailTemplateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
return emailTemplateResolver;
}
...
Read more about Stereotype Annotations here.
#Bean is used to define a method as a producer, which tells Spring to use that method to retrieve an object of the method return type and inject that object as a dependency whenever it's required.
#Component is used to define a class as a Spring component, which tells Spring to create an object (if it's Singleton) from and take care of it's lifecycle and dependencies and inject that object whenever it's required.
#Service and #Repository are basically just like #Component and AFAIK they are just for better grouping of your components.
#Service for Defining your service classes where you have your business logic, and #Repository for Defining your repository classes where you interact with an underlying system like database.
#Component
If we mark a class with #Component or one of the other Stereotype annotations these classes will be auto-detected using classpath scanning. As long as these classes are in under our base package or Spring is aware of another package to scan, a new bean will be created for each of these classes.
package com.beanvscomponent.controller;
import org.springframework.stereotype.Controller;
#Controller
public class HomeController {
public String home(){
return "Hello, World!";
}
}
There's an implicit one-to-one mapping between the annotated class and the bean (i.e. one bean per class). Control of wiring is quite limited with this approach since it's purely declarative. It is also important to note that the stereotype annotations are class level annotations.
#Bean
#Bean is used to explicitly declare a single bean, rather than letting Spring do it automatically like we did with #Controller. It decouples the declaration of the bean from the class definition and lets you create and configure beans exactly how you choose. With #Bean you aren't placing this annotation at the class level. If you tried to do that you would get an invalid type error. The #Bean documentation defines it as:
Indicates that a method produces a bean to be managed by the Spring container.
Typically, #Bean methods are declared within #Configuration classes.We have a user class that we needed to instantiate and then create a bean using that instance. This is where I said earlier that we have a little more control over how the bean is defined.
package com.beanvscomponent;
public class User {
private String first;
private String last;
public User(String first, String last) {
this.first = first;
this.last = last;
}
}
As i mentioned earlier #Bean methods should be declared within #Configuration classes.
package com.beanvscomponent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class ApplicationConfig {
#Bean
public User superUser() {
return new User("Partho","Bappy");
}
}
The name of the method is actually going to be the name of our bean. If we pull up the /beans endpoint in the actuator we can see the bean defined.
{
"beans": "superUser",
"aliases": [],
"scope": "singleton",
"type": "com.beanvscomponent.User",
"resource": "class path resource
[com/beanvscomponent/ApplicationConfig.class]",
"dependencies": []
}
#Component vs #Bean
I hope that cleared up some things on when to use #Component and when to use #Bean. It can be a little confusing but as you start to write more applications it will become pretty natural.

Spring Boot JPA Repository : Access JPA repository functions from normal java class in spring boot [duplicate]

Note: This is intended to be a canonical answer for a common problem.
I have a Spring #Service class (MileageFeeCalculator) that has an #Autowired field (rateService), but the field is null when I try to use it. The logs show that both the MileageFeeCalculator bean and the MileageRateService bean are being created, but I get a NullPointerException whenever I try to call the mileageCharge method on my service bean. Why isn't Spring autowiring the field?
Controller class:
#Controller
public class MileageFeeController {
#RequestMapping("/mileage/{miles}")
#ResponseBody
public float mileageFee(#PathVariable int miles) {
MileageFeeCalculator calc = new MileageFeeCalculator();
return calc.mileageCharge(miles);
}
}
Service class:
#Service
public class MileageFeeCalculator {
#Autowired
private MileageRateService rateService; // <--- should be autowired, is null
public float mileageCharge(final int miles) {
return (miles * rateService.ratePerMile()); // <--- throws NPE
}
}
Service bean that should be autowired in MileageFeeCalculator but it isn't:
#Service
public class MileageRateService {
public float ratePerMile() {
return 0.565f;
}
}
When I try to GET /mileage/3, I get this exception:
java.lang.NullPointerException: null
at com.chrylis.example.spring_autowired_npe.MileageFeeCalculator.mileageCharge(MileageFeeCalculator.java:13)
at com.chrylis.example.spring_autowired_npe.MileageFeeController.mileageFee(MileageFeeController.java:14)
...
The field annotated #Autowired is null because Spring doesn't know about the copy of MileageFeeCalculator that you created with new and didn't know to autowire it.
The Spring Inversion of Control (IoC) container has three main logical components: a registry (called the ApplicationContext) of components (beans) that are available to be used by the application, a configurer system that injects objects' dependencies into them by matching up the dependencies with beans in the context, and a dependency solver that can look at a configuration of many different beans and determine how to instantiate and configure them in the necessary order.
The IoC container isn't magic, and it has no way of knowing about Java objects unless you somehow inform it of them. When you call new, the JVM instantiates a copy of the new object and hands it straight to you--it never goes through the configuration process. There are three ways that you can get your beans configured.
I have posted all of this code, using Spring Boot to launch, at this GitHub project; you can look at a full running project for each approach to see everything you need to make it work. Tag with the NullPointerException: nonworking
Inject your beans
The most preferable option is to let Spring autowire all of your beans; this requires the least amount of code and is the most maintainable. To make the autowiring work like you wanted, also autowire the MileageFeeCalculator like this:
#Controller
public class MileageFeeController {
#Autowired
private MileageFeeCalculator calc;
#RequestMapping("/mileage/{miles}")
#ResponseBody
public float mileageFee(#PathVariable int miles) {
return calc.mileageCharge(miles);
}
}
If you need to create a new instance of your service object for different requests, you can still use injection by using the Spring bean scopes.
Tag that works by injecting the #MileageFeeCalculator service object: working-inject-bean
Use #Configurable
If you really need objects created with new to be autowired, you can use the Spring #Configurable annotation along with AspectJ compile-time weaving to inject your objects. This approach inserts code into your object's constructor that alerts Spring that it's being created so that Spring can configure the new instance. This requires a bit of configuration in your build (such as compiling with ajc) and turning on Spring's runtime configuration handlers (#EnableSpringConfigured with the JavaConfig syntax). This approach is used by the Roo Active Record system to allow new instances of your entities to get the necessary persistence information injected.
#Service
#Configurable
public class MileageFeeCalculator {
#Autowired
private MileageRateService rateService;
public float mileageCharge(final int miles) {
return (miles * rateService.ratePerMile());
}
}
Tag that works by using #Configurable on the service object: working-configurable
Manual bean lookup: not recommended
This approach is suitable only for interfacing with legacy code in special situations. It is nearly always preferable to create a singleton adapter class that Spring can autowire and the legacy code can call, but it is possible to directly ask the Spring application context for a bean.
To do this, you need a class to which Spring can give a reference to the ApplicationContext object:
#Component
public class ApplicationContextHolder implements ApplicationContextAware {
private static ApplicationContext context;
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static ApplicationContext getContext() {
return context;
}
}
Then your legacy code can call getContext() and retrieve the beans it needs:
#Controller
public class MileageFeeController {
#RequestMapping("/mileage/{miles}")
#ResponseBody
public float mileageFee(#PathVariable int miles) {
MileageFeeCalculator calc = ApplicationContextHolder.getContext().getBean(MileageFeeCalculator.class);
return calc.mileageCharge(miles);
}
}
Tag that works by manually looking up the service object in the Spring context: working-manual-lookup
If you are not coding a web application, make sure your class in which #Autowiring is done is a spring bean. Typically, spring container won't be aware of the class which we might think of as a spring bean. We have to tell the Spring container about our spring classes.
This can be achieved by configuring in appln-contxt or the better way is to annotate class as #Component and please do not create the annotated class using new operator.
Make sure you get it from Appln-context as below.
#Component
public class MyDemo {
#Autowired
private MyService myService;
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("test");
ApplicationContext ctx=new ClassPathXmlApplicationContext("spring.xml");
System.out.println("ctx>>"+ctx);
Customer c1=null;
MyDemo myDemo=ctx.getBean(MyDemo.class);
System.out.println(myDemo);
myDemo.callService(ctx);
}
public void callService(ApplicationContext ctx) {
// TODO Auto-generated method stub
System.out.println("---callService---");
System.out.println(myService);
myService.callMydao();
}
}
Actually, you should use either JVM managed Objects or Spring-managed Object to invoke methods.
from your above code in your controller class, you are creating a new object to call your service class which has an auto-wired object.
MileageFeeCalculator calc = new MileageFeeCalculator();
so it won't work that way.
The solution makes this MileageFeeCalculator as an auto-wired object in the Controller itself.
Change your Controller class like below.
#Controller
public class MileageFeeController {
#Autowired
MileageFeeCalculator calc;
#RequestMapping("/mileage/{miles}")
#ResponseBody
public float mileageFee(#PathVariable int miles) {
return calc.mileageCharge(miles);
}
}
I once encountered the same issue when I was not quite used to the life in the IoC world. The #Autowired field of one of my beans is null at runtime.
The root cause is, instead of using the auto-created bean maintained by the Spring IoC container (whose #Autowired field is indeed properly injected), I am newing my own instance of that bean type and using it. Of course this one's #Autowired field is null because Spring has no chance to inject it.
Your problem is new (object creation in java style)
MileageFeeCalculator calc = new MileageFeeCalculator();
With annotation #Service, #Component, #Configuration beans are created in the
application context of Spring when server is started. But when we create objects
using new operator the object is not registered in application context which is already created. For Example Employee.java class i have used.
Check this out:
public class ConfiguredTenantScopedBeanProcessor implements BeanFactoryPostProcessor {
#Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
String name = "tenant";
System.out.println("Bean factory post processor is initialized");
beanFactory.registerScope("employee", new Employee());
Assert.state(beanFactory instanceof BeanDefinitionRegistry,
"BeanFactory was not a BeanDefinitionRegistry, so CustomScope cannot be used.");
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
for (String beanName : beanFactory.getBeanDefinitionNames()) {
BeanDefinition definition = beanFactory.getBeanDefinition(beanName);
if (name.equals(definition.getScope())) {
BeanDefinitionHolder proxyHolder = ScopedProxyUtils.createScopedProxy(new BeanDefinitionHolder(definition, beanName), registry, true);
registry.registerBeanDefinition(beanName, proxyHolder.getBeanDefinition());
}
}
}
}
I'm new to Spring, but I discovered this working solution. Please tell me if it's a deprecable way.
I make Spring inject applicationContext in this bean:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
#Component
public class SpringUtils {
public static ApplicationContext ctx;
/**
* Make Spring inject the application context
* and save it on a static variable,
* so that it can be accessed from any point in the application.
*/
#Autowired
private void setApplicationContext(ApplicationContext applicationContext) {
ctx = applicationContext;
}
}
You can put this code also in the main application class if you want.
Other classes can use it like this:
MyBean myBean = (MyBean)SpringUtils.ctx.getBean(MyBean.class);
In this way any bean can be obtained by any object in the application (also intantiated with new) and in a static way.
It seems to be rare case but here is what happened to me:
We used #Inject instead of #Autowired which is javaee standard supported by Spring. Every places it worked fine and the beans injected correctly, instead of one place. The bean injection seems the same
#Inject
Calculator myCalculator
At last we found that the error was that we (actually, the Eclipse auto complete feature) imported com.opensymphony.xwork2.Inject instead of javax.inject.Inject !
So to summarize, make sure that your annotations (#Autowired, #Inject, #Service ,... ) have correct packages!
What hasn't been mentioned here is described in this article in the paragraph "Order of execution".
After "learning" that I had to annotate a class with #Component or the derivatives #Service or #Repository (I guess there are more), to autowire other components inside them, it struck me that these other components still were null inside the constructor of the parent component.
Using #PostConstruct solves that:
#SpringBootApplication
public class Application {
#Autowired MyComponent comp;
}
and:
#Component
public class MyComponent {
#Autowired ComponentDAO dao;
public MyComponent() {
// dao is null here
}
#PostConstruct
public void init() {
// dao is initialized here
}
}
One of the below will work :
The class where you are using #Autowired is not a Bean (You may have used new() somewhere I am sure).
Inside the SpringConfig class you have not mentioned the packages the Spring should look for #Component ( I am talking about #ComponentScan(basePackages"here") )
If above two don't work .... start putting System.out.println() and figure out where it is going wrong.
If this is happening in a test class, make sure you haven't forgotten to annotate the class.
For example, in Spring Boot:
#RunWith(SpringRunner.class)
#SpringBootTest
public class MyTests {
....
Some time elapses...
Spring Boot continues to evolve. It is no longer required to use #RunWith if you use the correct version of JUnit.
For #SpringBootTest to work stand alone, you need to use #Test from JUnit5 instead of JUnit4.
//import org.junit.Test; // JUnit4
import org.junit.jupiter.api.Test; // JUnit5
#SpringBootTest
public class MyTests {
....
If you get this configuration wrong your tests will compile, but #Autowired and #Value fields (for example) will be null. Since Spring Boot operates by magic, you may have few avenues for directly debugging this failure.
In simple words there are mainly two reasons for an #Autowired field to be null
YOUR CLASS IS NOT A SPRING BEAN.
The class in which you define the #Autowire anotation is not a spring bean. Thus spring will not auto wire the members.
THE FIELD IS NOT A BEAN.
There is no bean with the type or type in hierarchy you specified in the #Autowired field is not yet present in the spring application context or registry
Another solution would be to put a call of
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this)
to MileageFeeCalculator constructor like this:
#Service
public class MileageFeeCalculator {
#Autowired
private MileageRateService rateService; // <--- will be autowired when constructor is called
public MileageFeeCalculator() {
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this)
}
public float mileageCharge(final int miles) {
return (miles * rateService.ratePerMile());
}
}
I think you have missed to instruct spring to scan classes with annotation.
You can use #ComponentScan("packageToScan") on the configuration class of your spring application to instruct spring to scan.
#Service, #Component etc annotations add meta description.
Spring only injects instances of those classes which are either created as bean or marked with annotation.
Classes marked with annotation need to be identified by spring before injecting, #ComponentScan instruct spring look for the classes marked with annotation. When Spring finds #Autowired it searches for the related bean, and injects the required instance.
Adding annotation only, does not fix or facilitate the dependency injection, Spring needs to know where to look for.
This is the culprit of giving NullPointerException MileageFeeCalculator calc = new MileageFeeCalculator(); We are using Spring - don't need to create object manually. Object creation will be taken care of by IoC container.
UPDATE: Really smart people were quick to point on this answer, which explains the weirdness, described below
ORIGINAL ANSWER:
I don't know if it helps anyone, but I was stuck with the same problem even while doing things seemingly right. In my Main method, I have a code like this:
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {
"common.xml",
"token.xml",
"pep-config.xml" });
TokenInitializer ti = context.getBean(TokenInitializer.class);
and in a token.xml file I've had a line
<context:component-scan base-package="package.path"/>
I noticed that the package.path does no longer exist, so I've just dropped the line for good.
And after that, NPE started coming in. In a pep-config.xml I had just 2 beans:
<bean id="someAbac" class="com.pep.SomeAbac" init-method="init"/>
<bean id="settings" class="com.pep.Settings"/>
and SomeAbac class has a property declared as
#Autowired private Settings settings;
for some unknown reason, settings is null in init(), when <context:component-scan/> element is not present at all, but when it's present and has some bs as a basePackage, everything works well. This line now looks like this:
<context:component-scan base-package="some.shit"/>
and it works. May be someone can provide an explanation, but for me it's enough right now )
Also note that if, for whatever reason, you make a method in a #Service as final, the autowired beans you will access from it will always be null.
You can also fix this issue using #Service annotation on service class and passing the required bean classA as a parameter to the other beans classB constructor and annotate the constructor of classB with #Autowired. Sample snippet here :
#Service
public class ClassB {
private ClassA classA;
#Autowired
public ClassB(ClassA classA) {
this.classA = classA;
}
public void useClassAObjectHere(){
classA.callMethodOnObjectA();
}
}
This is only valid in case of Unit test.
My Service class had an annotation of service and it was #autowired another component class. When I tested the component class was coming null. Because for service class I was creating the object using new
If you are writing unit test make sure you are not creating object using new object(). Use instead injectMock.
This fixed my issue. Here is a useful link
Not entirely related to the question, but if the field injection is null, the constructor based injection will still work fine.
private OrderingClient orderingClient;
private Sales2Client sales2Client;
private Settings2Client settings2Client;
#Autowired
public BrinkWebTool(OrderingClient orderingClient, Sales2Client sales2Client, Settings2Client settings2Client) {
this.orderingClient = orderingClient;
this.sales2Client = sales2Client;
this.settings2Client = settings2Client;
}
In addition, don't inject to a static member, it will be null.
if you are using a private method, it will be null, try to change private to public in controller.

#Autowire failing with #Repository

I am not being able to make #Autowire annotation work with a #Repository annotated class.
I have an interface:
public interface AccountRepository {
public Account findByUsername(String username);
public Account findById(long id);
public Account save(Account account);
}
And the class implementing the interface annotated with #Repository:
#Repository
public class AccountRepositoryImpl implements AccountRepository {
public Account findByUsername(String username){
//Implementing code
}
public Account findById(long id){
//Implementing code
}
public Account save(Account account){
//Implementing code
}
}
In another class, I need to use this repository to find an account by the username, so I am using autowiring, but I am checking if it works and the accountRepository instance is always null:
#Component
public class FooClass {
#Autowired
private AccountRepository accountRepository;
...
public barMethod(){
logger.debug(accountRepository == null ? "accountRepository is NULL" : "accountRepository IS NOT NULL");
}
}
I have also set the packages to scan for the components (sessionFactory.setPackagesToScan(new String [] {"com.foo.bar"});), and it does autowire other classes annotated with #Component for instance, but in this one annotated with #Repository, it is always null.
Am I missing something?
Your problem is most likely that you're instantiating the bean yourself with new, so that Spring isn't aware of it. Inject the bean instead, or make the bean #Configurable and use AspectJ.
It seems likely that you haven't configured your Spring annotations to be enabled. I would recommend taking a look at your component scanning annotations. For instance in a Java config application:
#ComponentScan(basePackages = { "com.foo" })
... or XML config:
<context:annotation-config />
<context:component-scan base-package="com.foo" />
If your FooClass is not under the base-packages defined in that configuration, then the #Autowired will be ignored.
As an additional point, I would recommend trying #Autowired(required = true) - that should cause your application to fail on start-up rather than waiting until you use the service to throw a NullPointerException. However, if annotations are not configured, then there will be no failure.
You should test that your autowiring is being done correctly, using a JUnit test.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(
classes = MyConfig.class,
loader = AnnotationConfigContextLoader.class)
public class AccountRepositoryTest {
#Autowired
private AccountRepository accountRepository;
#Test
public void shouldWireRepository() {
assertNotNull(accountRepository);
}
}
This should indicate whether your basic configuration is correct. The next step, assuming that this is being deployed as a web application, would be to check that you have put the correct bits and pieces in your web.xml and foo-servlet.xml configurations to trigger Spring initialisation.
FooClass needs to be instancied by Spring to have his depencies managed.
Make sure FooClass is instancied as a bean (#Component or #Service annotation, or XML declaration).
Edit : sessionFactory.setPackagesToScan is looking for JPA/Hibernate annotations whereas #Repository is a Spring Context annotation.
AccountRepositoryImpl should be in the Spring component-scan scope
Regards,

How to initialize List inside Object using Spring Annotation

How do I initialize List inside Object using Spring Annotation
#Component
class Accounts{
private List<Transaction> _transaction;
//getter setter
}
How do I initialize List<Transaction> _transaction; using Spring Annotation or else i
have to define it in xml file.
But i dont want to write any xml file
You can use the Spring Java #Configuration for such a task:
#Configuration
public class SpringConfig {
#Bean
public List<Transaction> transactions() {
...... //Your logic to generate the list..
return transactions;
}
}
And in your Accounts class you have to use #Resource, not #Autowired, the semantics of injecting a list is a little different - if you use #Autowired, any bean of the same type will get injected into the list.
#Component
class Accounts{
#Resource(name="transactions")
private List<Transaction> _transaction;
//getter setter
}
This is pure java solution and there is no xml involved in creating the list..
If Transaction is a Bean with #Service, #Component or #Repository Annotation, you can just write #Autowired on top of your field.
#Component
class Accounts{
#Autowired
private List<Transaction> _transaction;
//getter setter
}

Resources