ContainerRequestFilter + #Autowired + Null for DAO - spring

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

Related

Autowiring of Service and Service Implementation class

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.

spring boot take interface as bean impletation

when I config spring boot 1.5 with mybatis multi-datasource, the classic error "Parameter 0 of constructor in SimsCardTypeController required a single bean, but 2 were found:aImpl,A" come out.
here is the related classes:
#RestController
#RequestMapping("/xx")
public class SimsCardTypeController extends RestBase {
private A simsCardTypeService;
private HttpServletRequest request;
#Autowired
public SimsCardTypeController(A simsCardTypeService, HttpServletRequest request) {
this.simsCardTypeService = simsCardTypeService;
this.request = request;
}
..
}
#Component
public class RestBase {}
interface A{}
#Service
class AImpl implements A{}
I don't know any possible config leading Spring take A as a bean. How can I debug this situation?
This is a problem with mybatis scan, mybatis transform A interface to a mapper.I share a tip to debug the similar problem:
1.qualify the strange interface A to the bean which Spring ask for
#Autowired
public SimsCardTypeController(#Qualifier(value="A")A simsCardTypeService, HttpServletRequest request){}
2. add breakpoint in the body,you can see what the simsCardTypeService exact is. In my case,it's something like xxMapper, so I can relate it to mybatis scan.
thanks

Spring Boot | MyBatis project structure can't wire layers

Can't wire layers in Spring Boot | MyBatis application. The problem is probably happening when Service layer uses Mapper.
Controller method sample:
#Controller
#RequestMapping("demo")
public class MessageController {
#Autowired
private MessageService messageService;
#RequestMapping(value = "messages", method = RequestMethod.GET)
public String getMessages(ModelMap modelMap) {
modelMap.addAttribute(MESSAGE,
messageService.selectMessages());
return "messages";
}
Service class:
#Service
public class MessageService {
#Autowired // Not sure if I can use Autowired here.
private MessageMapper messageMapper;
public MessageService() {
}
public Collection<Message> selectMessages() { return
messageMapper.selectAll(); }
}
MyBatis Mapper:
#Mapper
public interface MessageMapper {
#Select("select * from message")
Collection<Message> selectAll();
}
UPDATE
It feels like I'm having some fundamental knowledge based mistake. Probably managing external libraries.
Here's maven pom.xml. Looks kind of overloaded, I faced a lot of errors managing different spring-boot packages. Starter for autoconfiguration included.
pom.xml
Here's the project structure:
UPDATE #2
I'm sure DB connection is working well, I'm able to track changes in MySQL Workbench while Spring Boot is executing schema.sql and data.sql. But somehow, MyBatis mapper methods throw NullPointerException and page proceeds with exit code 500. Seems like they can't connect.
MessageService isn't managed by spring.
You have to annotate the MessageService class with #Service annotation (also, after adding this annotation you can indeed use #Autowired inside the service class)
#Service
public class MessageService {
#Autowired
private MessageMapper messageMapper;
public Collection<Message> selectMessages() {
return messageMapper.selectAll();
}
}
and wire it to the controller with
#Autowired
private MessageService messageService
and use it in a method like this
#RequestMapping(value = "messages", method = RequestMethod.GET)
public String getMessages(ModelMap modelMap) {
modelMap.addAttribute(MESSAGE, messageService.selectMessages());
return "messages";
}

#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,

RemoteServiceServlet with spring autowired gives nullpointerexception

I'm using GWT with Spring. I encountered the problem of using an #Autowired bean in a RemoteServiceServlet. For some reason this doesn't work automatically and I need to use #Configurable to get this working. I followed this approach but I still get a NullPointerException for the #Autowired bean:
#Configurable
#Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public class AServiceImpl extends RemoteServiceServlet implements AService {
#Autowired
private IABean aBean;
#Override
public void aMethodFromAService(Args arg[]) {
aBean.aMethodOfABean(); // this gives a NullPointerException
}
}
#Component
public class ABean implements IABean {
...
}
Any guidance in what is going on? Any extra information I need to provide?
http://mitosome.blogspot.be/2011/01/injecting-spring-beans-into-gwt.html
Thanks Alexander for putting me in the right direction
You found a workable solution, but just for the record and we have it working as follows:
public class MyServiceImpl extends RemoteServiceServlet
implements MyService, ServletContextAware
{
#Autowired private transient SomeService someService;
....
}
and
<context:annotation-config/>
<context:component-scan base-package="..."/>
The SomeService is a completely vanilla XML-defined bean. Perhaps that or ...implements ServletContextAware makes a difference.
Cheers,

Resources