A field with #Autowired annotation
it works if the field is in a class with the annotation #Controller
but it does not work if the field is in a class with the annotation #Component
¿Can someone tell me how should I put a field with the #Autowired annotation in a class that has the #Component annotation?
Thanks and regards
In the class Modelo1Controller
#Controller
public class Modelo1Controller {
#Autowired
private SelectUtil selectUtil;
the selectUtil field has value and works correctly
But in the class Modelo
#Component
public class Modelo extends BeanCommon implements Serializable {
#Autowired
private SelectUtil selectUtil;
When I try to use the selectUtil field the value is null and I get NullPointerException
String text = selectUtil.getDescripcionBienText(value);
java.lang.NullPointerException: null
And the class SelectUtil
#Component
public class SelectUtil {
Finally I have made my application work
The main problem was that I used the new operator to instantiate the object in another code block
Every day I'm learning new Spring concepts
In any case, thanks and maybe the problem and the solution can be used by more people in the same situation
Related
Does #Value field injection require to be under a #RestController / #Configuration class for it to work?
I went through countless tutorials no one seem to mention anything like it, but wen I tried on my own code it just doesn't work. I found suppose solution here: Spring Boot application.properties value not populating
But it didn't work in my case.
public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {
#Value("${token.secret}")
private String tokenSecret; <--- always null
#Value("${token.expiration_time}")
private String tokenTime; <--- always null
...
#PostConstruct <-- this was suggested but still null
public void init(){
log.info("tokenTime : {}", tokenTime);
log.info("tokenSecret: {}", tokenSecret);
}
}
I then moved these fields to my #Configuration or #RestController class the values does get populated, why is that? and how to fix this in my AuthenticationFilter?
#Configuration
#EnableWebSecurity
public class AppWebSecurity extends WebSecurityConfigurerAdapter {
#Value("${token.secret}")
private String tokenSecret;
#Value("${token.expiration_time}")
private String tokenTime;
....
}
Thank you
Following are my code
#RestController
public class EmployeeController {
#Autowired
EmployeeService empService;
public EmployeeController (EmployeeService Impl empServiceImpl) {
super();
this.empService = empServiceImpl;
}
}
#Service
public interface EmployeeService {
public List<EmployeeDTO> getAllEmployeeDetails()
}
public class EmployeeServiceImpl {
public List<EmployeeDTO> getAllEmployeeDetails(){
//methods business logic and repo call goes here
}
}
When I start my server I am getting below error.
Parameter 1 of constructor in
com.app.in.controller.EmployeeController required a bean of type
'com.app.in.service.EmployeeServiceImpl' that could not be found
My understanding might be wrong. If I annotate the EmployeeSeriveImpl class also with #Service then it working.Is that is the correct way to do it ? My question is the service interface is annotated with #Service still why its implementation is also required to annotation. Please let me know if I miss something in that ? What is the standard method to solve this issue ?
You can get your dependency injected using a constructor. And #Autowired is optional in this case.
This is your example, but with a few corrections:
#RestController
public class EmployeeController {
// private final is a good practice. no need in #Autowire
private final EmployeeService empService;
// this constructor will be used to inject your dependency
// #Autowired is optional in this case, but you can put it here
public EmployeeController (EmployeeService empServiceImpl) {
this.empService = empServiceImpl;
}
}
I assume you have an interface EmployeeService and class EmployeeServiceImpl which implements that interface and is Spring Bean.
Something like this:
#Service
public class EmployeeServiceImpl implements EmployeeService {}
Why this #Service is needed? When you put this annotation on your class, Spring knows this is a bean that Spring should manage for you (container will create an instance of it and inject it wherever it is needed).
Check Spring docs to get more details about Dependency Injection.
The Spring team generally advocates constructor injection, as it lets you implement application components as immutable objects and ensures that required dependencies are not null.
I am implementing the Basic auth for RestEasy API. I tried to implement javax.ws.rs.container.ContainerRequestFilter with annotation #Provider. Everything looks clean until i tried #Autowired my DAO class in my implementation class. Initially, i hard coded my Username & Password in the implemented class and it works. Finally, i started integrating with my DAO class to get those values from DB. But #Autowired annotation is returning null for my DAO. I tried googling and tried lot of option, but still i am getting null for that DAO.
I have annotated my DAO class with #Repository.
#Provider
public class SecurityInterceptor implements javax.ws.rs.container.ContainerRequestFilter {
#Autowired
private SecurityDao securityDao;
...
#Repository("securityDao")
public class SecurityDaoImpl implements SecurityDao {
Can someone help me in this issue?
Thanks in advance!
Edit -
#ApplicationPath("/")
public class RestApplication extends Application{
#Override
public Set<Object> getSingletons()
{
Set<Object> singletons = new HashSet<Object>();
singletons.add(new SecurityInterceptor());
return singletons;
}
}
I think i see same issue in this post also.Spring autowired dao is null. Did anyone have solution for this issue? Please let me know. Thanks
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
}
I am using Spring in my Java Application, all the #Autowired annotations working until now.
Simplified example would be:
#Component
public class MyBean implements MyInterface {
...
}
#Component
public class MyOtherBean {
#Autowired
private MyBean myBean;
...
}
Once I try to start the Application, I get:
java.lang.IllegalArgumentException: Can not set MyBean field MyOtherBean.myBean to $ProxyXX
The interface contains just two public simple methods and the class implements them.
Both classes are public and have public default constructor. (I even tried to instantiate them in tests.
Once I remove the implements section, everything works correctly.
What can be wrong with the implementation of the interface? What is $ProxyXX?
I suspect the issue is that Spring is injecting an AOP proxy which implements MyInterface - possibly for the purposes of transaction management or caching. Are any of MyBean's methods annotated #Transactional or annotated with any other annotation?
Ideally you'd probably want to reference MyBean by it's interface type - which should resolve the issue.
#Component
public class MyOtherBean {
#Autowired
private MyInterface myBean;
...
}
If you have more than one bean implementing MyInterface then you an always qualify your bean by name.
#Component
public class MyOtherBean {
#Autowired
#Qualifier("myBean")
private MyInterface myBean;
...
}
By default, Spring uses Java dynamic proxies to implement AOP when the bean implements an interface. The easiest and cleanest way to solve your problem is to make program on interfaces, and inject theinterface insted of the concrete class:
#Component
public class MyOtherBean {
#Autowired
private MyInterface myBean;
...
}
See http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/htmlsingle/#aop-proxying for how to force Spring to always use CGLib.