Issue: As a producer, If I wanted to use ReplyingKafkaTemplate,
I would be configuring only KafkaMessageListenerContainer
but auto configuration gets failed with below logs
KafkaConfiguration.java:
#Autowired
private KafkaProperties properties;
#Bean
public ConsumerFactory<Long, String> cf() {
return new DefaultKafkaConsumerFactory<>
(properties.getConsumer().buildProperties());
}
#Bean
public KafkaMessageListenerContainer<String, String>
container() {
ContainerProperties props = new ContainerProperties("replies");
KafkaMessageListenerContainer<Long, String> container
= new KafkaMessageListenerContainer<>(cf(),props);
return container;
}
#Bean
public ReplyingKafkaTemplate<Long, String, String> replyingKafkaTemplate(KafkaMessageListenerContainer<Long, String> container ){
return new ReplyingKafkaTemplate<Long, Order, String>(pf()), container);
}
Below Autoconfiguration in KafkaAnnotationDrivenConfiguration causing this issue:
#Bean
#ConditionalOnMissingBean(name = "kafkaListenerContainerFactory")
public ConcurrentKafkaListenerContainerFactory<?, ?> kafkaListenerContainerFactory(
ConcurrentKafkaListenerContainerFactoryConfigurer configurer,ConsumerFactory<Object, Object> kafkaConsumerFactory) {}
Logs:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'kafkaListenerContainerFactory' defined in class path resource [org/springframework/boot/autoconfigure/kafka/KafkaAnnotationDrivenConfiguration.class]: Unsatisfied dependency expressed through method 'kafkaListenerContainerFactory' parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.kafka.core.ConsumerFactory<java.lang.Object, java.lang.Object>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:767) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:508) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1288) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863) ~[spring-context-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546) ~[spring-context-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) [spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) [spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) [spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) [spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE]
at com.barath.app.KafkaProducerApplication.main(KafkaProducerApplication.java:10) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_101]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_101]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_101]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_101]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.1.0.RELEASE.jar:2.1.0.RELEASE]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.kafka.core.ConsumerFactory<java.lang.Object, java.lang.Object>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1646) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1205) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1166) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:855) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:758) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
... 24 common frames omitted
Updated:
As pointed out in the answer, issue caused due to custom creation of consumer factory. Using of auto configuration has resolved the issue.
PS: I can avoid this issue by creating a bean of type ConsumerFactory but just wanted to know whether it can be controlled as part of auto configuration itself
You need to show all your configuration (pf, cf etc).
However, you seem to be confusing container and factory.
KafkaMessageListenerContainer is not a container factory, it is a container.
That said, I think you are over complicating things - just use Boot's auto configured factory to create the reply container. This works fine for me...
public class So53573729Application {
public static void main(String[] args) {
SpringApplication.run(So53573729Application.class, args);
}
#Bean
public ConcurrentMessageListenerContainer<Long, String> repliesContainer(
ConcurrentKafkaListenerContainerFactory<Long, String> containerFactory) {
ConcurrentMessageListenerContainer<Long, String> repliesContainer =
containerFactory.createContainer("replies");
repliesContainer.getContainerProperties().setGroupId("repliesGroup");
repliesContainer.setAutoStartup(false);
return repliesContainer;
}
#Bean
public ReplyingKafkaTemplate<Long, String, String> replyingTemplate(
ProducerFactory<Long, String> pf,
ConcurrentMessageListenerContainer<Long, String> repliesContainer) {
return new ReplyingKafkaTemplate<>(pf, repliesContainer);
}
}
Related
I'm trying to implement a function in my application to create an entity. I have tried coding analog to sample code of my professor which works. Instead I get an exception upon trying to create a new article.
My class: Article.java
#Entity
#Inheritance(strategy = InheritanceType.JOINED)
#Table(name = "ArticleData")
#NamedQuery(name = "Article.getArticle", query = "Select a from Article a where a.articleName = :articleName and a.articlePrice= :articlePrice")
public class Article implements Serializable{
private double articlePrice;
#Id
private String articleName;
public Article(){
}
public Article(String articleName, double articlePrice){
this.articleName = articleName;
this.articlePrice = articlePrice;
}
The Bean: ArticleBean.java
#Named
#SessionScoped
public class ArticleBean implements Serializable{
private static final Logger logger = LogManager.getLogger(ArticleBean.class);
private static final long serialVersionUID = 7730144564841961508L;
#EJB
private ArticleController articleController;
private Article articleData;
public ArticleBean() {
}
//Trying to do this
public String addArticle(){
String forward, caption, msg;
logger.debug("initiate adding of article");
FacesContext contect = FacesContext.getCurrentInstance();
articleController.newArticle(articleData.getArticleName(), articleData.getArticlePrice());
return "addarticle.xhtml";
}
ArticleController.java
#Stateless
public class ArticleController {
#EJB
ArticleFacade articleManager;
private static final Logger logger = LogManager.getLogger(AccountController.class);
public void newArticle(String articleName, double articlePrice){
logger.info("try to create article " + articleName);
logger.info("price: " + articlePrice);
Article newArticle = new Article(articleName, articlePrice);
try{
articleManager.create(newArticle);
}catch (Exception e){
logger.error(e.getMessage());
}
}
ArticleFacade.java
public class ArticleFacade extends AbstractFacade<Article>{
#PersistenceContext(unitName = "examAdminPU")
private EntityManager em;
public ArticleFacade() {
super(Article.class);
}
#Override
public EntityManager getEntityManager() {
return em;
}
public void setEm(EntityManager em) {
this.em = em;
}
}
Here is a sample of the stacktrace
SCHWERWIEGEND: ejb.stateless_ejbcreate_exception
WARNUNG: A system exception occurred during an invocation on EJB ArticleController, method: public void de.hspf.swt.exam.administration.control.ArticleController.newArticle(java.lang.String,double)
WARNUNG: javax.ejb.EJBException: javax.ejb.EJBException: javax.ejb.CreateException: Could not create stateless EJB
at com.sun.ejb.containers.StatelessSessionContainer._getContext(StatelessSessionContainer.java:439)
at com.sun.ejb.containers.BaseContainer.getContext(BaseContainer.java:2667)
at com.sun.ejb.containers.BaseContainer.preInvoke(BaseContainer.java:2044)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:210)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:90)
at com.sun.proxy.$Proxy555.newArticle(Unknown Source)
at de.hspf.swt.exam.administration.control.__EJB31_Generated__ArticleController__Intf____Bean__.newArticle(Unknown Source)
at de.hspf.swt.exam.administration.cdi.ArticleBean.addArticle(ArticleBean.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at javax.el.ELUtil.invokeMethod(ELUtil.java:263)
at javax.el.BeanELResolver.invoke(BeanELResolver.java:494)
at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:215)
at com.sun.el.parser.AstValue.invoke(AstValue.java:285)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at org.jboss.weld.module.web.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
at org.jboss.weld.module.web.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:65)
at com.sun.faces.application.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:66)
at com.sun.faces.application.ActionListenerImpl.getNavigationOutcome(ActionListenerImpl.java:82)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:71)
at javax.faces.component.UICommand.broadcast(UICommand.java:222)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:847)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1395)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:58)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:76)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:177)
at javax.faces.webapp.FacesServlet.executeLifecyle(FacesServlet.java:707)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:451)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1628)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:258)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:755)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:575)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:159)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:371)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:238)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:520)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:217)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:182)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:156)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:218)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:95)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:260)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:177)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:109)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:88)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:53)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:524)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:89)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:94)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$0(WorkerThreadIOStrategy.java:90)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:114)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:569)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:549)
at java.lang.Thread.run(Thread.java:748)
Caused by: javax.ejb.EJBException: javax.ejb.CreateException: Could not create stateless EJB
at com.sun.ejb.containers.StatelessSessionContainer$SessionContextFactory.create(StatelessSessionContainer.java:708)
at com.sun.ejb.containers.util.pool.NonBlockingPool.getObject(NonBlockingPool.java:219)
at com.sun.ejb.containers.StatelessSessionContainer._getContext(StatelessSessionContainer.java:435)
... 58 more
Caused by: javax.ejb.CreateException: Could not create stateless EJB
at com.sun.ejb.containers.StatelessSessionContainer.createStatelessEJB(StatelessSessionContainer.java:518)
at com.sun.ejb.containers.StatelessSessionContainer.access$000(StatelessSessionContainer.java:92)
at com.sun.ejb.containers.StatelessSessionContainer$SessionContextFactory.create(StatelessSessionContainer.java:706)
... 60 more
Caused by: java.lang.IllegalStateException: Exception attempting to inject Remote ejb-ref name=de.hspf.swt.exam.administration.control.ArticleController/articleManager,Remote 3.x interface =de.hspf.swt.exam.administration.dao.facade.ArticleFacade,ejb-link=null,lookup=,mappedName=,jndi-name=de.hspf.swt.exam.administration.dao.facade.ArticleFacade,refType=Session into class de.hspf.swt.exam.administration.control.ArticleController: Lookup failed for 'java:comp/env/de.hspf.swt.exam.administration.control.ArticleController/articleManager' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming}
at org.glassfish.weld.services.InjectionServicesImpl.aroundInject(InjectionServicesImpl.java:194)
at org.jboss.weld.injection.InjectionContextImpl.run(InjectionContextImpl.java:46)
at org.jboss.weld.injection.producer.DefaultInjector.inject(DefaultInjector.java:73)
at org.jboss.weld.module.ejb.DynamicInjectionPointInjector.inject(DynamicInjectionPointInjector.java:61)
at org.jboss.weld.module.ejb.SessionBeanInjectionTarget.inject(SessionBeanInjectionTarget.java:138)
at org.glassfish.weld.services.JCDIServiceImpl.injectEJBInstance(JCDIServiceImpl.java:314)
at com.sun.ejb.containers.BaseContainer.injectEjbInstance(BaseContainer.java:1845)
at com.sun.ejb.containers.StatelessSessionContainer.createStatelessEJB(StatelessSessionContainer.java:479)
... 62 more
Caused by: com.sun.enterprise.container.common.spi.util.InjectionException: Exception attempting to inject Remote ejb-ref name=de.hspf.swt.exam.administration.control.ArticleController/articleManager,Remote 3.x interface =de.hspf.swt.exam.administration.dao.facade.ArticleFacade,ejb-link=null,lookup=,mappedName=,jndi-name=de.hspf.swt.exam.administration.dao.facade.ArticleFacade,refType=Session into class de.hspf.swt.exam.administration.control.ArticleController: Lookup failed for 'java:comp/env/de.hspf.swt.exam.administration.control.ArticleController/articleManager' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming}
at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl._inject(InjectionManagerImpl.java:638)
at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.inject(InjectionManagerImpl.java:439)
at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.injectInstance(InjectionManagerImpl.java:153)
at org.glassfish.weld.services.InjectionServicesImpl.aroundInject(InjectionServicesImpl.java:184)
... 69 more
Caused by: javax.naming.NamingException: Lookup failed for 'java:comp/env/de.hspf.swt.exam.administration.control.ArticleController/articleManager' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NamingException: Exception resolving Ejb for 'Remote ejb-ref name=de.hspf.swt.exam.administration.control.ArticleController/articleManager,Remote 3.x interface =de.hspf.swt.exam.administration.dao.facade.ArticleFacade,ejb-link=null,lookup=,mappedName=,jndi-name=de.hspf.swt.exam.administration.dao.facade.ArticleFacade,refType=Session' . Actual (possibly internal) Remote JNDI name used for lookup is 'de.hspf.swt.exam.administration.dao.facade.ArticleFacade#de.hspf.swt.exam.administration.dao.facade.ArticleFacade' [Root exception is javax.naming.NamingException: Lookup failed for 'de.hspf.swt.exam.administration.dao.facade.ArticleFacade#de.hspf.swt.exam.administration.dao.facade.ArticleFacade' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: de.hspf.swt.exam.administration.dao.facade.ArticleFacade#de.hspf.swt.exam.administration.dao.facade.ArticleFacade not found]]]
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:496)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:442)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
at com.sun.enterprise.container.common.impl.util.InjectionManagerImpl._inject(InjectionManagerImpl.java:561)
... 72 more
Caused by: javax.naming.NamingException: Exception resolving Ejb for 'Remote ejb-ref name=de.hspf.swt.exam.administration.control.ArticleController/articleManager,Remote 3.x interface =de.hspf.swt.exam.administration.dao.facade.ArticleFacade,ejb-link=null,lookup=,mappedName=,jndi-name=de.hspf.swt.exam.administration.dao.facade.ArticleFacade,refType=Session' . Actual (possibly internal) Remote JNDI name used for lookup is 'de.hspf.swt.exam.administration.dao.facade.ArticleFacade#de.hspf.swt.exam.administration.dao.facade.ArticleFacade' [Root exception is javax.naming.NamingException: Lookup failed for 'de.hspf.swt.exam.administration.dao.facade.ArticleFacade#de.hspf.swt.exam.administration.dao.facade.ArticleFacade' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: de.hspf.swt.exam.administration.dao.facade.ArticleFacade#de.hspf.swt.exam.administration.dao.facade.ArticleFacade not found]]
at com.sun.ejb.EjbNamingReferenceManagerImpl.resolveEjbReference(EjbNamingReferenceManagerImpl.java:185)
at com.sun.enterprise.container.common.impl.ComponentEnvManagerImpl$EjbReferenceProxy.create(ComponentEnvManagerImpl.java:1015)
at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.lookup(GlassfishNamingManagerImpl.java:765)
at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.lookup(GlassfishNamingManagerImpl.java:735)
at com.sun.enterprise.naming.impl.JavaURLContext.lookup(JavaURLContext.java:159)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:476)
... 76 more
Caused by: javax.naming.NamingException: Lookup failed for 'de.hspf.swt.exam.administration.dao.facade.ArticleFacade#de.hspf.swt.exam.administration.dao.facade.ArticleFacade' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: de.hspf.swt.exam.administration.dao.facade.ArticleFacade#de.hspf.swt.exam.administration.dao.facade.ArticleFacade not found]
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:496)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:442)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
at com.sun.ejb.EjbNamingReferenceManagerImpl.resolveEjbReference(EjbNamingReferenceManagerImpl.java:180)
... 81 more
Caused by: javax.naming.NameNotFoundException: de.hspf.swt.exam.administration.dao.facade.ArticleFacade#de.hspf.swt.exam.administration.dao.facade.ArticleFacade not found
at com.sun.enterprise.naming.impl.TransientContext.doLookup(TransientContext.java:237)
at com.sun.enterprise.naming.impl.TransientContext.lookup(TransientContext.java:204)
at com.sun.enterprise.naming.impl.SerialContextProviderImpl.lookup(SerialContextProviderImpl.java:70)
at com.sun.enterprise.naming.impl.LocalSerialContextProviderImpl.lookup(LocalSerialContextProviderImpl.java:114)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:483)
... 85 more
I resolved it. I forgot to annotate that ArticleFacade.java is stateless.
#Stateless
public class ArticleController {
#EJB
ArticleFacade articleManager;
private static final Logger logger = LogManager.getLogger(AccountController.class);
public void newArticle(String articleName, double articlePrice){
logger.info("try to create article " + articleName);
logger.info("price: " + articlePrice);
Article newArticle = new Article(articleName, articlePrice);
try{
articleManager.create(newArticle);
}catch (Exception e){
logger.error(e.getMessage());
}
}
public void changeArticle(String articleName, double articlePrice){
logger.info("try to edit article " + articleName);
Article editArticle = new Article(articleName, articlePrice);
try{
articleManager.edit(editArticle);
}catch (Exception e){
logger.error(e.getMessage());
}
}
public void destroyArticle(String articleName, double articlePrice){
logger.info("try to remove article" + articleName);
Article deleteArticle = new Article(articleName, articlePrice);
try{
articleManager.remove(deleteArticle);
}catch (Exception e){
logger.error(e.getMessage());
}
}
}
I am facing issue with Integration Test on one of Controller Test in SpringBoot 1.4.
Below snippets will show a clear idea of project structure:
class ExchangeControllerIT :
public class ExchangeControllerIT extends AbstractSpringControllerIT {
// class under test
#Autowired
private ExchangeController exchangeController;
#Autowired
private OAuth2RestTemplate restTemplate;
#Test
public void shouldSuccessWhileExchange() throws Exception {
// given
controllerHas(mockExchangeServiceReturningStringResponse());
// then
getMockMvc().perform(get(Uris.Exchange).accept(MediaType.TEXT_HTML)
.content(asString(ExchangeControllerIT.class, "")))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.parseMediaType(MediaType.TEXT_HTML + ";charset=UTF-8")));
}
private void controllerHas(ExchangeService exchangeService) {
Reflections.setField(exchangeController, "exchangeService", exchangeService);
}
private static ExchangeService mockExchangeServiceReturningStringResponse() {
return new HandShakeService();
}
}
Abstract Class below:
public abstract class AbstractSpringControllerIT extends AbstractSpringIT{
protected MockMvc getMockMvc() {
return webAppContextSetup(getApplicationContext()).build();
}
}
AbstractSpringIT class:
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.DEFINED_PORT)
public abstract class AbstractSpringIT {
#Autowired(required=true)
private GenericWebApplicationContext ctx;
protected final GenericWebApplicationContext getApplicationContext() {
return ctx;
}
}
I am new to SpringBoot and Tests, help me find out cause and probable solution
StackTrace for above mentioned error:
java.lang.IllegalStateException: Unable to find a #SpringBootConfiguration, you need to use #ContextConfiguration or #SpringBootTest(classes=...) with your test
at org.springframework.util.Assert.state(Assert.java:392)
at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.getOrFindConfigurationClasses(SpringBootTestContextBootstrapper.java:173)
at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.processMergedContextConfiguration(SpringBootTestContextBootstrapper.java:133)
at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:409)
at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildDefaultMergedContextConfiguration(AbstractTestContextBootstrapper.java:323)
at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:277)
at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildTestContext(AbstractTestContextBootstrapper.java:112)
at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.buildTestContext(SpringBootTestContextBootstrapper.java:78)
at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:120)
at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:105)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTestContextManager(SpringJUnit4ClassRunner.java:152)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init>(SpringJUnit4ClassRunner.java:143)
at org.springframework.test.context.junit4.SpringRunner.<init>(SpringRunner.java:49)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:96)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Looks like even though you are using the #SpringBootTest annotation you are not including its classes parameter where you will need to specify the classes that you will need to be loaded in your context in order for your test to run successfully.
Check what classes you need and include them there:
#SpringBootTest(classes=...)
Also, although may be not the best solution, if you do not mind to reload the whole spring context for your test you could just use the #SpringBootConfiguration annotation in your test class instead of #SpringBootTest
I am developing Spring MVC+Security+MySQL example. I've taken a reference from http://www.mkyong.com/spring-security/spring-security-form-login-using-database/. In this project, I make some customization, in this I created "database.properties" file and trying to load it into the AppConfig.java. When I deployed this project I see below error coming. Please help!
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.setFilterChainProxySecurityConfigurer(org.springframework.security.config.annotation.ObjectPostProcessor,java.util.List) throws java.lang.Exception; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.mkyong.config.SecurityConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: javax.sql.DataSource com.mkyong.config.SecurityConfig.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class com.mkyong.config.AppConfig: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.jdbc.datasource.DriverManagerDataSource com.mkyong.config.AppConfig.dataSource()] threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [${mysql.jdbc.driver}]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1146)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:628)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:410)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4840)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5303)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1407)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1397)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.setFilterChainProxySecurityConfigurer(org.springframework.security.config.annotation.ObjectPostProcessor,java.util.List) throws java.lang.Exception; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.mkyong.config.SecurityConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: javax.sql.DataSource com.mkyong.config.SecurityConfig.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class com.mkyong.config.AppConfig: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.jdbc.datasource.DriverManagerDataSource com.mkyong.config.AppConfig.dataSource()] threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [${mysql.jdbc.driver}]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:604)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:286)
... 22 more
Caused by: org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.mkyong.config.SecurityConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: javax.sql.DataSource com.mkyong.config.SecurityConfig.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class com.mkyong.config.AppConfig: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.jdbc.datasource.DriverManagerDataSource com.mkyong.config.AppConfig.dataSource()] threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [${mysql.jdbc.driver}]
at org.springframework.context.expression.StandardBeanExpressionResolver.evaluate(StandardBeanExpressionResolver.java:142)
at org.springframework.beans.factory.support.AbstractBeanFactory.evaluateBeanDefinitionString(AbstractBeanFactory.java:1318)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:782)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:770)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
... 24 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.mkyong.config.SecurityConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: javax.sql.DataSource com.mkyong.config.SecurityConfig.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class com.mkyong.config.AppConfig: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.jdbc.datasource.DriverManagerDataSource com.mkyong.config.AppConfig.dataSource()] threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [${mysql.jdbc.driver}]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
My updated code, other files are unchanged.
database.properties
mysql.jdbc.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/test
mysql.username=root
mysql.password=root
AppConfig.java
#EnableWebMvc
#Configuration
#ComponentScan({ "com.mkyong.web.*" })
#Import({ SecurityConfig.class })
#PropertySource({"classpath:database.properties"})
public class AppConfig {
#Value("${mysql.jdbc.driver}")
private String driverClass;
#Value("${mysql.url}")
private String url;
#Value("${mysql.username}")
private String username;
#Value("${mysql.password}")
private String password;
#Bean(name = "dataSource")
public DriverManagerDataSource dataSource() {
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
/*driverManagerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
driverManagerDataSource.setUrl("jdbc:mysql://localhost:3306/test");
driverManagerDataSource.setUsername("root");
driverManagerDataSource.setPassword("root");*/
driverManagerDataSource.setDriverClassName(driverClass);
driverManagerDataSource.setUrl(url);
driverManagerDataSource.setUsername(username);
driverManagerDataSource.setPassword(password);
return driverManagerDataSource;
}
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
java.lang.IllegalStateException: Could not load JDBC driver class
[${mysql.jdbc.driver}]
Actually, the place holder ${mysql.jdbc.driver} is not resolved.
You can have following placeholder configurer bean which will resolve this value placeholders.
#Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
PropertySourcesPlaceholderConfigurer
Specialization of PlaceholderConfigurerSupport that resolves ${...}
placeholders within bean definition property values and #Value
annotations against the current Spring Environment and its set of
PropertySources.
You can get the value form the properties file using the environment variable made by the spring when initialize the configuration. I think , this is the best and clear way to get the value from the properties file , if you are using spring.
Getting the value directly from Environment Variable
//other annotation
#PropertySource(value = { "properties file path" })
public class AppConfig{
#Autowired
private Environment environment;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
return dataSource;
}
I am trying to use Shiro 1.2.2 with my SpringMVC 3.2.3 I have seen several examples of how to configure Shiro using ini files. But we are using JavaConfig and I have only found one partial example on that. I have several #Configuration files:
public class EdmWebInitializer implements WebApplicationInitializer {
private static final String DISPATCHER_SERVLET_NAME = "dispatcher";
private static final String DISPATCHER_SERVLET_MAPPING = "/*";
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
root.scan( "com.company.config" );
root.register( EdmConfiguration.class, SecurityConfig.class );
servletContext.addListener( new ContextLoaderListener( root ) );
ServletRegistration.Dynamic appServlet = servletContext.addServlet( DISPATCHER_SERVLET_NAME,
new DispatcherServlet( root ) );
appServlet.setLoadOnStartup( 1 );
Set<String> mappingConflicts = appServlet.addMapping( DISPATCHER_SERVLET_MAPPING );
servletContext
.addFilter( "shiroFilter", new DelegatingFilterProxy( "shiroFilter", root ) )
.addMappingForUrlPatterns( null, false, DISPATCHER_SERVLET_MAPPING );
servletContext.addFilter( "Spring OpenEntityManagerInViewFilter",
org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.class ).addMappingForUrlPatterns(
null, false, "/*" );
My beans are defined here:
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = { "com.company.service", "com.company.utility",
"com.company.controller", "com.company.utility.startup",
"com.company.security", "com.company.security.model" })
#EnableTransactionManagement
#ImportResource({ "classpath:applicationContext.xml"})
#PropertySource({ "classpath:application.properties", "classpath:mail.properties" })
public class EdmConfiguration extends WebMvcConfigurationSupport {
#Resource
private Environment environment;
#Autowired
private org.apache.shiro.web.mgt.WebSecurityManager securityManager;
#Bean
public DataSource dataSource() {
BoneCPDataSource dataSource = new BoneCPDataSource();
...
return dataSource;
}
#Bean
public JpaTransactionManager transactionManager() throws ClassNotFoundException {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory( entityManagerFactoryBean().getObject() );
return transactionManager;
}
#Bean
public DelegatingFilterProxy springSecurityFilterChain() {
return new DelegatingFilterProxy();
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() throws ClassNotFoundException {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource( dataSource() );
entityManagerFactoryBean.setPackagesToScan( environment
.getRequiredProperty( PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN ) );
entityManagerFactoryBean.setPersistenceProviderClass( HibernatePersistence.class );
Properties jpaProperties = new Properties();
...
entityManagerFactoryBean.setJpaProperties( jpaProperties );
return entityManagerFactoryBean;
}
#Bean
public PersistenceExceptionTranslator exTranslator() {
return new HibernateExceptionTranslator();
}
#Bean(initMethod = "init")
public StartupListener startupListener() {
return new StartupListener();
}
#Bean
public ContentNegotiationManagerFactoryBean contentNegotiationManager() {
Properties properties = new Properties();
properties.setProperty( "xml", "application/xml" );
properties.setProperty( "json", "application/json" );
properties.setProperty( "html", "application/html" );
ContentNegotiationManagerFactoryBean contentNegotiationManager = new ContentNegotiationManagerFactoryBean();
contentNegotiationManager.setFavorParameter( true );
contentNegotiationManager.setMediaTypes( properties );
contentNegotiationManager.setDefaultContentType( MediaType.APPLICATION_JSON );
return contentNegotiationManager;
}
#Bean
public JavaMailSenderImpl mailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
int port = Integer.parseInt( environment.getRequiredProperty( "mail.smtp.socketFactory.port" ) );
mailSender.setHost( environment.getRequiredProperty( "mail.smtp.host" ) );
mailSender.setPort( port );
mailSender.setUsername( environment.getRequiredProperty( "mail.login.username" ) );
mailSender.setPassword( environment.getRequiredProperty( "mail.login.password" ) );
Properties properties = new Properties();
properties.setProperty( "mail.smtp.auth", environment.getRequiredProperty( "mail.smtp.auth" ) );
properties.setProperty( "mail.smtp.starttls.enable", "true" );
mailSender.setJavaMailProperties( properties );
return mailSender;
}
#Bean
public VelocityEngine getVelocityEngine() throws VelocityException, IOException {
VelocityEngineFactory factory = new VelocityEngineFactory();
Properties props = new Properties();
props.put( "resource.loader", "class" );
props.put( "class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader" );
factory.setVelocityProperties( props );
factory.setResourceLoaderPath( "/com/edelweissco/dental/templates" );
factory.setPreferFileSystemAccess( false );
return factory.createVelocityEngine();
}
#Bean
public StandardPasswordEncoder encoder() {
return new org.springframework.security.crypto.password.StandardPasswordEncoder();
}
#Bean
public ShiroFilterFactoryBean shiroFilter() {
ShiroFilterFactoryBean shiroFilter = new org.apache.shiro.spring.web.ShiroFilterFactoryBean();
shiroFilter.setSecurityManager( securityManager);
return shiroFilter;
}
#Bean
#DependsOn(value = "lifecycleBeanPostProcessor")
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator creator = new DefaultAdvisorAutoProxyCreator();
creator.setProxyTargetClass(true); // it's false by default
return creator;
}
I have broken the Shiro configuraton into its own file:
#Configuration
public class SecurityConfig {
#Bean
public CustomSecurityRealm customSecurityRealm() {
return new CustomSecurityRealm();
}
#Bean
public SaltAwareJdbcRealm saltAwareJdbcRealm() {
return new SaltAwareJdbcRealm();
}
#Bean
public org.apache.shiro.authc.credential.DefaultPasswordService passwordService() {
return new DefaultPasswordService();
}
#Bean
public TempFixPasswordMatcher passwordMatcher() {
TempFixPasswordMatcher tempFixPasswordMatcher = new TempFixPasswordMatcher();
tempFixPasswordMatcher.setPasswordService( passwordService() );
return tempFixPasswordMatcher;
}
#Bean
public WebSecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm( saltAwareJdbcRealm() );
return securityManager;
}
#Bean
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
#Bean
public MethodInvokingFactoryBean methodInvokingFactoryBean() {
MethodInvokingFactoryBean methodInvokingFactoryBean = new MethodInvokingFactoryBean();
methodInvokingFactoryBean.setStaticMethod( "org.apache.shiro.SecurityUtils.setSecurityManager" );
methodInvokingFactoryBean.setArguments( new Object[]{ securityManager() } );
return methodInvokingFactoryBean;
}
#Bean
#DependsOn(value = "lifecycleBeanPostProcessor")
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
return new DefaultAdvisorAutoProxyCreator();
}
#Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager( securityManager() );
return authorizationAttributeSourceAdvisor;
}
When I try to deploy I get exceptions such as :
This is the full stack trace I get once I remove the #Transaction from my OfficeService:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'menuService': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'menuRepository': Post-processing of the FactoryBean's object failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class com.sun.proxy.$Proxy68]: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class class com.sun.proxy.$Proxy68
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:306)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1116)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:626)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4937)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1551)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:301)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:835)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:771)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:622)
at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:569)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:301)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:835)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:771)
at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1455)
at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:75)
at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1296)
at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1388)
at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:819)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:303)
at sun.rmi.transport.Transport$1.run(Transport.java:159)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:155)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:535)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:790)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:649)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
at java.lang.Thread.run(Thread.java:680)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'menuRepository': Post-processing of the FactoryBean's object failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class com.sun.proxy.$Proxy68]: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class class com.sun.proxy.$Proxy68
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:165)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:102)
at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1454)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:442)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:416)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:550)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:150)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:303)
... 55 more
Caused by: org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class com.sun.proxy.$Proxy68]: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class class com.sun.proxy.$Proxy68
at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:217)
at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:111)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(AbstractAutoProxyCreator.java:477)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:362)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:322)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:409)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.postProcessObjectFromFactoryBean(AbstractAutowireCapableBeanFactory.java:1625)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:162)
... 65 more
Caused by: java.lang.IllegalArgumentException: Cannot subclass final class class com.sun.proxy.$Proxy68
at org.springframework.cglib.proxy.Enhancer.generateClass(Enhancer.java:446)
at org.springframework.cglib.transform.TransformingClassGenerator.generateClass(TransformingClassGenerator.java:33)
at org.springframework.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:377)
at org.springframework.cglib.proxy.Enhancer.create(Enhancer.java:285)
at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:205)
... 72 more
Nov 9, 2013 4:10:04 PM org.apache.catalina.core.ApplicationContext log
INFO: Closing Spring root WebApplicationContext
Presumably you have some #RequiresAuthentication or #RequiresRole annotations on your service classes. To enable those, Shiro (Spring) has to proxy the beans it creates. It does this with the DefaultAdvisorAutoProxyCreator bean. However, this bean proxies with JDK proxies which create proxies based on interfaces, not on base classes.
For example, say Spring has to proxy OfficeService, it'll create a java.lang.reflect.Proxy instance that wraps the OfficeService bean. If you called getClass() on this object, it would return something like com.sun.proxy.$Proxy64. If your OfficeService was implementing any interfaces, that object would be an instance of those interfaces. However, the bean is not an instance of OfficeService, so Spring can't use it as an #Autowired target.
Instead, you have to tell Spring to use CGLIB proxies. You can do that by changing your config here
#Bean
#DependsOn(value = "lifecycleBeanPostProcessor")
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator creator = new DefaultAdvisorAutoProxyCreator();
creator.setProxyTargetClass(true); // it's false by default
return creator;
}
And adding the CGLIB libraries (jars) to your classpath.
Note that if this is not a Shiro issue, you need to post the rest of your config. If you are doing any other proxying in your context, you'll need to do something similar to disable JDK proxies.
It seems like the only other thing that can create proxies is the transaction management, so change to
#EnableTransactionManagement(proxyTargetClass = true)
I'm newbie to spring mvc & had a problem with Junit test case for spring MVC
controller with resteasy.I tried out for sample implementation of junit
test case, but getting exception.
my code is.....
spring MVC controller
#Controller
#Path("/sample")
public class SampleController {
#Autowired
Article article;
public SampleController() {
System.out.println("cons()");
}
#GET
#Path("/get")
#Produces("text/html")
public String testPost()
{
System.out.println("Inside Get");
article.getName();
return "Hello";
}
}
Junit Test Case for controller
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("classpath:/springmvc-servlet.xml" )
public class SampleControllerTest {
#Autowired
protected ApplicationContext context;
protected MockHttpServletRequest request;
protected MockHttpServletResponse response;
private AnnotationMethodHandlerAdapter adapter;
#Autowired
private SampleController controller;
#Before
public void setUp() {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
response.setOutputStreamAccessAllowed(true);
adapter = new AnnotationMethodHandlerAdapter();
}
#Test
public void testTestPost() {
request.setMethod("GET");
request.setRequestURI("/sample/get");
try {
adapter.handle(request, response, controller);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Exception
org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException: No matching handler method found for servlet request: path '/sample/get', method 'GET', parameters map[[empty]]
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodResolver.resolveHandlerMethod(AnnotationMethodHandlerAdapter.java:626)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:421)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
at in.nic.cmf.springmvc.SampleControllerTest.testTestPost(SampleControllerTest.java:50)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
I need test case for spring mvc with resteasy....
Thanx in Advance!
When I checked it MVC integration it doesn't work. I switched to plain Spring integration "40.1. Basic Integration".
Regards