Search Results

Search found 80 results on 4 pages for 'autowired'.

Page 1/4 | 1 2 3 4  | Next Page >

  • Is context:annotation-config an alternative to @AutoWired?

    - by Antacid
    Is it correct that I can put context:annotation-config in my XML config and it will automatically inject the bean class without needing any annotations? So instead of using these annotation types: public class Mailman { private String name; @Autowired private Parcel Parcel; public Mailman(String name) { this.name = name; } @Autowired public void setParcel(Parcel Parcel) { this.Parcel = Parcel; } @Autowired public void directionsToParcel(Parcel Parcel) { this.Parcel = Parcel; } } I would just need to write this: <beans ... > <bean id="mailMan" class="MailMan"> <constructor-arg value="John Doe"/> </bean> <bean id="parcel" class="Parcel" /> <context:annotation-config /> </beans> and then my MailMan class would look a lot simpler without the need for annotations: public class Mailman { private String name; private Parcel Parcel; public Mailman(String name) { this.name = name; } }

    Read the article

  • How to override the behavior of Spring @Autowired

    - by Mark
    Hi a little background: I am Using Spring 2.5, and specifically spring IOC and annotations. I am using @Autowired in my code (the Autowiring is done by type) and use @Component for exposing Classes to the Automatic wiring. The situation described bellow arose while i tried to test my code. now to the problem: Note: i use a different Spring Context for the Test environment. I have a class FOO which is @Autowired but in the test context i want to use a different class of the same type MockFoo (extends FOO) The Spring Setup of course fails do so automatically due to multiple options for the Dependency Injection of the FOO class (both FOO and MockFOO comply to the Type check) I am looking for a way to inject the test bean instead of the original bean. I expected Spring to allow using the Context configurion file to override a bean injection or to order Spring not to autowire a specific bean BUT All these option seem to exists only for the beans which were originally defined in the Spring Context Configuration file

    Read the article

  • spring-nullpointerexception- cant access autowired annotated service (or dao) in a no-annotations class

    - by user286806
    I have this problem that I cannot fix. From my @Controller, i can easily access my autowired @Service class and play with it no problem. But when I do that from a separate class without annotations, it gives me a NullPointerException. My Controller (works)- @Controller public class UserController { @Autowired UserService userService;... My separate Java class (not working)- public final class UsersManagementUtil { @Autowired UserService userService; or @Autowired UserDao userDao; userService or userDao are always null! Was just trying if any one of them works. My component scan setting has the root level package set for scanning so that should be OK. my servlet context - <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <!-- the application context definition for the springapp DispatcherServlet --> <!-- Enable annotation driven controllers, validation etc... --> <context:property-placeholder location="classpath:jdbc.properties" /> <context:component-scan base-package="x" /> <tx:annotation-driven transaction-manager="hibernateTransactionManager" /> <!-- package shortended --> <bean id="messageSource" class="o.s.c.s.ReloadableResourceBundleMessageSource"> <property name="basename" value="/WEB-INF/messages" /> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${database.driver}" /> <property name="url" value="${database.url}" /> <property name="username" value="${database.user}" /> <property name="password" value="${database.password}" /> </bean> <!-- package shortened --> <bean id="viewResolver" class="o.s.w.s.v.InternalResourceViewResolver"> <property name="prefix"> <value>/</value> </property> <property name="suffix"> <value>.jsp</value> </property> <property name="order"> <value>0</value> </property> </bean> <!-- package shortened --> <bean id="sessionFactory" class="o.s.o.h3.a.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="annotatedClasses"> <list> <value>orion.core.models.Question</value> <value>orion.core.models.User</value> <value>orion.core.models.Space</value> <value>orion.core.models.UserSkill</value> <value>orion.core.models.Question</value> <value>orion.core.models.Rating</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> </props> </property> </bean> <bean id="hibernateTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> Any clue?

    Read the article

  • inject a mockups to a bean that has @autowired annotations

    - by santiagozky
    I have a bean that has a couple of beans injected with the autowire annotation (no qualifier). Now, for testing reasons I want to inject some mocks to the bean instead of the ones being autowired (some DAOs). Is there any way I can change which bean is being injected without modifying my bean? I don't like the idea of adding annotations my code just to test it and then remove then for production. I am using spring 2.5. The bean look like this: @Transactional @Service("validaBusinesService") public class ValidaBusinesServiceImpl implements ValidaBusinesService { @Autowired OperationDAO operationDAO; @Autowired BinDAO binDAO; @Autowired CardDAO cardDAO; @Autowired UserDAO userDAO; ... ... }

    Read the article

  • Spring @Autowired and WebApplicationContext in Tomcat

    - by EugeneP
    @Autowired works only once. What to do to make it wire the bean every time the Servlet is recreated? My web-app (Tomcat6 container) consists of 2 Servlets. Every servlet has private fields. Their setters are marked with @Autowired In the init method I use WebApplicationContextUtils ... autowireBean(this); It autowires the properties marked with @Autowired once - during the initialization of the Servlet. Any other session will see these fields values, they will not be rewired after the previous session is destroyed. What to do to make them rewire them each time a Servlet constructor is called? a) Put the autowiring into the constructor? Or better 2) get a web app context and extract a bean from there?

    Read the article

  • Spring 3 DI using generic DAO interface

    - by Peders
    I'm trying to use @Autowired annotation with my generic Dao interface like this: public interface DaoContainer<E extends DomainObject> { public int numberOfItems(); // Other methods omitted for brevity } I use this interface in my Controller in following fashion: @Configurable public class HelloWorld { @Autowired private DaoContainer<Notification> notificationContainer; @Autowired private DaoContainer<User> userContainer; // Implementation omitted for brevity } I've configured my application context with following configuration <context:spring-configured /> <context:component-scan base-package="com.organization.sample"> <context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation" /> </context:component-scan> <tx:annotation-driven /> This works only partially, since Spring creates and injects only one instance of my DaoContainer, namely DaoContainer. In other words, if I ask userContainer.numberOfItems(); I get the number of notificationContainer.numberOfItems() I've tried to use strongly typed interfaces to mark the correct implementation like this: public interface NotificationContainer extends DaoContainer<Notification> { } public interface UserContainer extends DaoContainer<User> { } And then used these interfaces like this: @Configurable public class HelloWorld { @Autowired private NotificationContainer notificationContainer; @Autowired private UserContainer userContainer; // Implementation omitted... } Sadly this fails to BeanCreationException: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.organization.sample.dao.NotificationContainer com.organization.sample.HelloWorld.notificationContainer; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.organization.sample.NotificationContainer] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} Now, I'm a little confused how should I proceed or is using multiple Dao's even possible. Any help would be greatly appreciated :)

    Read the article

  • <jaxrs:client> not getting autowired

    - by himangshu
    I am trying to build a restful client using jaxrs:client as defined in http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/resources/jaxrs_soap_rest/WEB-INF/beans.xml In my test class I am getting org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.abc.service.ExportServiceTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.bankbazaar.service.ExportService com.abc.service.ExportServiceTest.exportClient; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.abc.service.ExportService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=exportClient)} this is my spring config However exportClient=(ExportService)applicationContext.getBean("exportClient"); this works. Thanks Himangshu

    Read the article

  • Is It Possible To Spring Autowire the same Instance of a protoype scoped class in two places

    - by Mark
    Hi ** changed the example to better express the situation i am using spring 2.5 and have the following situation @Component @Scope("prototype") Class Foo { } class A { @Autowired Foo fooA; } class B { @Autowired Foo fooB; } class C { @Autowired Foo fooC; } i am trying to understand if there is some way to use @Autowired and bind the same instance of FOO onto fooA and fooB while binding a different instance to fooC i understand that if the scope of FOO will be singleton it will work but i am wandering if there is a way to achieve the same goal while using a protoype scope. also please explain is this the correct usage of the autowiring concept ? am i trying to abuse the spring framework purpose

    Read the article

  • Spring configuration in GWT Project?

    - by Firstthumb
    I am developing a GWT-Spring-Hibernate project and I want to use Spring Autowired annotation in GWT Service Servlet but my autowired annotated service is not injected. it is null. Is there a configuration detail that I missed? I add <context:annotation-config /> <context:component-scan base-package="com.org" /> to my ApplicationContext.xml and I have annotated my service as @Service("myService") @Autowired MyService myService; // This is null so WHY?

    Read the article

  • Why doesn't the spring @Autowire work with java generics

    - by testing123
    Inspired by spring data awesomeness I wanted to create a abstract RESTController that I could extend for a lot of my controllers. I created the following class: @Controller public abstract class RESTController<E, PK extends Serializable, R extends PagingAndSortingRepository<E, PK>> { @Autowired private R repository; @RequestMapping(method=RequestMethod.GET, params={"id"}) @ResponseBody public E getEntity(@RequestParam PK id) { return repository.findOne(id); } ... } I was hoping that the generics would allow me to @Autowire in the repository but I get the following error: SEVERE: Allocate exception for servlet appServlet org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [org.springframework.data.repository.PagingAndSortingRepository] is defined: expected single matching bean but found 3: [groupRepository, externalCourseRepository, managedCourseRepository] at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:800) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294) I understand what the error is telling me, there is more than one match for the @Autowire. I am confused because I thought by creating the following controller it would work: @Controller @RequestMapping(value="/managedCourse") public class ManagedCourseController extends RESTController<ManagedCourse, Long, ManagedCourseRepository> { ... } This is easy enough to work around by doing having a method like this in the RESTController: protected abstract R getRepository(); and then doing this in your implementing class: @Autowired private ManagedCourseRepository repository; @Override protected ManagedCourseRepository getRepository() { return repository; } I was just wondering if someone had any thoughts of how I could get this to work.

    Read the article

  • deep injection - spring

    - by Bob
    What is the best way (or options) for accessing spring components at layers deep within the application that aren't managed by spring? For example, I have a low level utility POJO class into which I need to autowire/inject a spring component. I'll call it LowLevelHelper. There are multiple classes that use LowLevelHelper - most are layers away from anything that is hooked up with spring. One option would be to make all the layers in to spring components, but that seems like I'm hacking my design to force spring to help me. I have some complex things going on that won't be nearly as clean if I have to @Autowire all the pieces and don't new anything. Another option might be to manually inject the component in the low level class, but I'm not really sure if this is possible or the right solution.

    Read the article

  • Spring @Autowired messageSource working in Controller but not in other classes?

    - by Jayaprakash
    New updates: As I could not succeed in configuring messageSource through annotations, I attempted to configure messageSource injection through servlet-context.xml. I still have messageSource as null. Please let me know if you need any more specific info, and I will provide. Thanks for your help in advance. servlet-context.xml <beans:bean id="message" class="com.mycompany.myapp.domain.common.message.Message"> <beans:property name="messageSource" ref="messageSource" /> </beans:bean> Spring gives the below information message about spring initialization. INFO : org.springframework.context.annotation.ClassPathBeanDefinitionScanner - JSR-330 'javax.inject.Named' annotation found and supported for component scanning INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Overriding bean definition for bean 'message': replacing [Generic bean: class [com.mycompany.myapp.domain.common.message.Message]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [C:\springsource\tc-server-developer-2.1.0.RELEASE\spring-insight-instance\wtpwebapps\myapp\WEB-INF\classes\com\mycompany\myapp\domain\common\message\Message.class]] with [Generic bean: class [com.mycompany.myapp.domain.common.message.Message]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]] INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1c7caac5: defining beans [org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.validation.beanvalidation.LocalValidatorFactoryBean#0,org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0,org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#0,xxxDao,message,xxxService,jsonDateSerializer,xxxController,homeController,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,tilesViewResolver,tilesConfigurer,messageSource,org.springframework.web.servlet.handler.MappedInterceptor#1,localeResolver,org.springframework.web.servlet.view.ContentNegotiatingViewResolver#0,validator,resourceBundleLocator,messageInterpolator]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory@4f47af3 I have the below definition for message source in 3 classes. In debug mode, I can see that in class xxxController, messageSource is initialized to org.springframework.context.support.ReloadableResourceBundleMessageSource. I have annotated Message class with @Component and xxxHibernateDaoImpl with @Repository. I also included context namespace definition in servlet-context.xml. But in Message class and xxxHibernateDaoImpl class, the messageSource is still null. Why is Spring not initializing messageSource in the two other classes though in xxxController classes, it initializes correctly? @Controller public class xxxController{ @Autowired private ReloadableResourceBundleMessageSource messageSource; } @Component public class Message{ @Autowired private ReloadableResourceBundleMessageSource messageSource; } @Repository("xxxDao") public class xxxHibernateDaoImpl{ @Autowired private ReloadableResourceBundleMessageSource messageSource; } <beans:beans xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <beans:bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <beans:property name="basename" value="/resources/messages/messages" /> </beans:bean> <context:component-scan base-package="com.mycompany.myapp"/> </beans>

    Read the article

  • How can I qualify an autowired property with a variable from a config file using annotations?

    - by jiggy
    My specific problem is that I have configured two beans that implement the same interface and I have a third bean that has a property of that interface's type. I inject the property using a config property. So, assuming RemoteDataSource and LocalDataSource implement IDataSource and dao1 has a property of type IDataSource, my XML config might look like this: <bean id="datasource1" class="com.foo.RemoteDataSource"> <property name="url">${url}</property> </bean> <bean id="datasource2" class="com.foo.LocalDataSource"> <property name="path">${filepath}</property> </bean> <bean id="dao1" class="com.foo.MyDAO"> <property name="dataSource">${datasource}</property> </bean> With url, filepath and datasource being defined in an included properties file. We are now making a push for annotation-driven configuration and I'm not sure how to annotate my dao to put the data source configured in the property file. I want to do something like this, but it is evidently not allowed: @Autowired @Qualifier("${datasource}") public void setDataSource(IDataSource datasource) {...}

    Read the article

  • Autowire not working in junit test

    - by Dave Paroulek
    I'm sure I'm missing something simple. bar gets autowired in the junit test, but why doesn't bar inside foo get autowired? @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"beans.xml"}) public class BarTest { @Autowired Object bar; @Test public void testBar() throws Exception { //this works assertEquals("expected", bar.someMethod()); //this doesn't work, because the bar object inside foo isn't autowired? Foo foo = new Foo(); assertEquals("expected", foo.someMethodThatUsesBar()); } }

    Read the article

  • Guice, JDBC and managing database connections

    - by pledge
    I'm looking to create a sample project while learning Guice which uses JDBC to read/write to a SQL database. However, after years of using Spring and letting it abstract away connection handling and transactions I'm struggling to work it our conceptually. I'd like to have a service which starts and stops a transaction and calls numerous repositories which reuse the same connection and participate in the same transaction. My questions are: Where do I create my Datasource? How do I give the repositories access to the connection? (ThreadLocal?) Best way to manage the transaction (Creating an Interceptor for an annotation?) The code below shows how I would do this in Spring. The JdbcOperations injected into each repository would have access to the connection associated with the active transaction. I haven't been able to find many tutorials which cover this, beyond ones which show creating interceptors for transactions. I am happy with continuing to use Spring as it is working very well in my projects, but I'd like to know how to do this in pure Guice and JBBC (No JPA/Hibernate/Warp/Reusing Spring) @Service public class MyService implements MyInterface { @Autowired private RepositoryA repositoryA; @Autowired private RepositoryB repositoryB; @Autowired private RepositoryC repositoryC; @Override @Transactional public void doSomeWork() { this.repositoryA.someInsert(); this.repositoryB.someUpdate(); this.repositoryC.someSelect(); } } @Repository public class MyRepositoryA implements RepositoryA { @Autowired private JdbcOperations jdbcOperations; @Override public void someInsert() { //use jdbcOperations to perform an insert } } @Repository public class MyRepositoryB implements RepositoryB { @Autowired private JdbcOperations jdbcOperations; @Override public void someUpdate() { //use jdbcOperations to perform an update } } @Repository public class MyRepositoryC implements RepositoryC { @Autowired private JdbcOperations jdbcOperations; @Override public String someSelect() { //use jdbcOperations to perform a select and use a RowMapper to produce results return "select result"; } }

    Read the article

  • Spring MVC configuration problems

    - by Smek
    i have some problems with configuring Spring MVC. I made a maven multi module project with the following modules: /api /domain /repositories /webapp I like to share the domain and the repositories between the api and the webapp (both web projects). First i want to configure the webapp to use the repositories module so i added the dependencies in the xml file like this: <dependency> <groupId>${project.groupId}</groupId> <artifactId>domain</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <dependency> <groupId>${project.groupId}</groupId> <artifactId>repositories</artifactId> <version>1.0-SNAPSHOT</version> </dependency> And my controller in the webapp module looks like this: package com.mywebapp.webapp; import com.mywebapp.domain.Person; import com.mywebapp.repositories.services.PersonService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping("/") @Configuration @ComponentScan("com.mywebapp.repositories") public class PersonController { @Autowired PersonService personservice; @RequestMapping(method = RequestMethod.GET) public String printWelcome(ModelMap model) { Person p = new Person(); p.age = 23; p.firstName = "John"; p.lastName = "Doe"; personservice.createNewPerson(p); model.addAttribute("message", "Hello world!"); return "index"; } } In my webapp module i try to load configuration files in my web.xml like this: <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/META-INF/persistence-context.xml, classpath:/META-INF/service-context.xml</param-value> </context-param> These files cannot be found so i get the following error: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [META-INF/persistence-context.xml]; nested exception is java.io.FileNotFoundException: class path resource [META-INF/persistence-context.xml] cannot be opened because it does not exist These files are in the repositories module so my first question is how can i make Spring to find these files? I also have trouble Autowiring the PersonService to my Controller class did i forget to configure something in my XML? Here is the error message: [INFO] [talledLocalContainer] SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener [INFO] [talledLocalContainer] org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.mywebapp.repositories.repository.PersonRepository com.mywebapp.repositories.services.PersonServiceImpl.personRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.mywebapp.repositories.repository.PersonRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} PersonServiceImple.java: package com.mywebapp.repositories.services; import com.mywebapp.domain.Person; import com.mywebapp.repositories.repository.PersonRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.stereotype.Service; @Service public class PersonServiceImpl implements PersonService{ @Autowired public PersonRepository personRepository; @Autowired public MongoTemplate personTemplate; @Override public Person createNewPerson(Person person) { return personRepository.save(person); } } PersonService.java package com.mywebapp.repositories.services; import com.mywebapp.domain.Person; public interface PersonService { Person createNewPerson(Person person); } PersonRepository.java: package com.mywebapp.repositories.repository; import com.mywebapp.domain.Person; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; import java.math.BigInteger; @Repository public interface PersonRepository extends MongoRepository<Person, BigInteger> { } persistance-context.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mongo="http://www.springframework.org/schema/data/mongo" xsi:schemaLocation= "http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <context:property-placeholder location="classpath:mongo.properties"/> <mongo:mongo host="${mongo.host}" port="${mongo.port}" id="mongo"> <mongo:options connections-per-host="${mongo.connectionsPerHost}" threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}" connect-timeout="${mongo.connectTimeout}" max-wait-time="${mongo.maxWaitTime}" auto-connect-retry="${mongo.autoConnectRetry}" socket-keep-alive="${mongo.socketKeepAlive}" socket-timeout="${mongo.socketTimeout}" slave-ok="${mongo.slaveOk}" write-number="1" write-timeout="0" write-fsync="true"/> </mongo:mongo> <mongo:db-factory dbname="person" mongo-ref="mongo" id="mongoDbFactory"/> <bean id="personTemplate" name="personTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/> </bean> <mongo:repositories base-package="com.mywebapp.repositories.repository" mongo-template-ref="personTemplate"> <mongo:repository id="personRepository" repository-impl-postfix="PersonRepository" mongo-template-ref="personTemplate" create-query-indexes="true"/> </mongo:repositories> Thanks

    Read the article

  • Problem with Autowiring & No unique bean

    - by mada
    I have 2 classes (B,C) extends class A. @Service public class A extends AbstratClass<Modele>{ @Autowired A(MyClass br) { super(br); } @Service public class B extends A{ @Autowired B (MyClass br) { super(br); } @Service public class C extends A{ @Autowired C (MyClass br) { super(br); } But i have this message: No unique bean of type [A] ] is defined: expected single matching bean but found 2: [A, B, moveModeleMarshaller] I really cant get why i have this message & how to resolve even after reading Spring documentation. Thanks in advance.

    Read the article

  • Spring Transactional Parameterized Test and Autowiring

    - by James Kingsbery
    Is there a way to get a class that extends AbstractTransactionalJUnit4SpringContexts to play nicely with JUnit's own @RunWith(Parameterized), so that fields marked as Autowired get wired in properly? @RunWith(Parameterized) public class Foo extends AbstractTransactionalJUnit4SpringContexts { @Autowired private Bar bar @Parameters public static Collection data() { // return parameters, following pattern in // http://junit.org/apidocs/org/junit/runners/Parameterized.html } @Test public void someTest(){ bar.baz() //NullPointerException } }

    Read the article

  • how to call service inside service layer

    - by cometta
    in my service layer public class MyServiceLayerImpl{ @Autowired MyServiceInterface MyServiceLayer } if i have method inside service layer that need to call another service inside service layer. i cannot use this._method ,because, i'm using AOP for caching. In order for the caching to work, i have to use @Autowired to get the service. Therefore, is the above style ok?

    Read the article

  • How can I resolve Hibernate 3's ConstraintViolationException when updating a Persistent Entity's Col

    - by Tim Visher
    I'm trying to discover why two nearly identical class sets are behaving different from Hibernate 3's perspective. I'm fairly new to Hibernate in general and I'm hoping I'm missing something fairly obvious about the mappings or timing issues or something along those lines but I spent the whole day yesterday staring at the two sets and any differences that would lead to one being able to be persisted and the other not completely escaped me. I appologize in advance for the length of this question but it all hinges around some pretty specific implementation details. I have the following class mapped with Annotations and managed by Hibernate 3.? (if the specific specific version turns out to be pertinent, I'll figure out what it is). Java version is 1.6. ... @Embeddable public class JobStateChange implements Comparable<JobStateChange> { @Temporal(TemporalType.TIMESTAMP) @Column(nullable = false) private Date date; @Enumerated(EnumType.STRING) @Column(nullable = false, length = JobState.FIELD_LENGTH) private JobState state; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "acting_user_id", nullable = false) private User actingUser; public JobStateChange() { } @Override public int compareTo(final JobStateChange o) { return this.date.compareTo(o.date); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } else if (!(obj instanceof JobStateChange)) { return false; } JobStateChange candidate = (JobStateChange) obj; return this.state == candidate.state && this.actingUser.equals(candidate.getUser()) && this.date.equals(candidate.getDate()); } @Override public int hashCode() { return this.state.hashCode() + this.actingUser.hashCode() + this.date.hashCode(); } } It is mapped as a Hibernate CollectionOfElements in the class Job as follows: ... @Entity @Table( name = "job", uniqueConstraints = { @UniqueConstraint( columnNames = { "agency", //Job Name "payment_type", //Job Name "payment_file", //Job Name "date_of_payment", "payment_control_number", "truck_number" }) }) public class Job implements Serializable { private static final long serialVersionUID = -1131729422634638834L; ... @org.hibernate.annotations.CollectionOfElements @JoinTable(name = "job_state", joinColumns = @JoinColumn(name = "job_id")) @Sort(type = SortType.NATURAL) private final SortedSet<JobStateChange> stateChanges = new TreeSet<JobStateChange>(); ... public void advanceState( final User actor, final Date date) { JobState nextState; LOGGER.debug("Current state of {} is {}.", this, this.getCurrentState()); if (null == this.currentState) { nextState = JobState.BEGINNING; } else { if (!this.isAdvanceable()) { throw new IllegalAdvancementException(this.currentState.illegalAdvancementStateMessage); } if (this.currentState.isDivergent()) { nextState = this.currentState.getNextState(this); } else { nextState = this.currentState.getNextState(); } } JobStateChange stateChange = new JobStateChange(nextState, actor, date); this.setCurrentState(stateChange.getState()); this.stateChanges.add(stateChange); LOGGER.debug("Advanced {} to {}", this, this.getCurrentState()); } private void setCurrentState(final JobState jobState) { this.currentState = jobState; } boolean isAdvanceable() { return this.getCurrentState().isAdvanceable(this); } ... @Override public boolean equals(final Object obj) { if (obj == this) { return true; } else if (!(obj instanceof Job)) { return false; } Job otherJob = (Job) obj; return this.getName().equals(otherJob.getName()) && this.getDateOfPayment().equals(otherJob.getDateOfPayment()) && this.getPaymentControlNumber().equals(otherJob.getPaymentControlNumber()) && this.getTruckNumber().equals(otherJob.getTruckNumber()); } @Override public int hashCode() { return this.getName().hashCode() + this.getDateOfPayment().hashCode() + this.getPaymentControlNumber().hashCode() + this.getTruckNumber().hashCode(); } ... } The purpose of JobStateChange is to record when the Job moves through a series of State Changes that are outline in JobState as enums which know about advancement and decrement rules. The interface used to advance Jobs through a series of states is to call Job.advanceState() with a Date and a User. If the Job is advanceable according to rules coded in the enum, then a new StateChange is added to the SortedSet and everyone's happy. If not, an IllegalAdvancementException is thrown. The DDL this generates is as follows: ... drop table job; drop table job_state; ... create table job ( id bigint generated by default as identity, current_state varchar(25), date_of_payment date not null, beginningCheckNumber varchar(8) not null, item_count integer, agency varchar(10) not null, payment_file varchar(25) not null, payment_type varchar(25) not null, endingCheckNumber varchar(8) not null, payment_control_number varchar(4) not null, truck_number varchar(255) not null, wrapping_system_type varchar(15) not null, printer_id bigint, primary key (id), unique (agency, payment_type, payment_file, date_of_payment, payment_control_number, truck_number) ); create table job_state ( job_id bigint not null, acting_user_id bigint not null, date timestamp not null, state varchar(25) not null, primary key (job_id, acting_user_id, date, state) ); ... alter table job add constraint FK19BBD12FB9D70 foreign key (printer_id) references printer; alter table job_state add constraint FK57C2418FED1F0D21 foreign key (acting_user_id) references app_user; alter table job_state add constraint FK57C2418FABE090B3 foreign key (job_id) references job; ... The database is seeded with the following data prior to running tests ... insert into job (id, agency, payment_type, payment_file, payment_control_number, date_of_payment, beginningCheckNumber, endingCheckNumber, item_count, current_state, printer_id, wrapping_system_type, truck_number) values (-3, 'RRB', 'Monthly', 'Monthly','4501','1998-12-01 08:31:16' , '00000001','00040000', 40000, 'UNASSIGNED', null, 'KERN', '02'); insert into job_state (job_id, acting_user_id, date, state) values (-3, -1, '1998-11-30 08:31:17', 'UNASSIGNED'); ... After the database schema is automatically generated and rebuilt by the Hibernate tool. The following test runs fine up until the call to Session.flush() ... @ContextConfiguration(locations = { "/applicationContext-data.xml", "/applicationContext-service.xml" }) public class JobDaoIntegrationTest extends AbstractTransactionalJUnit4SpringContextTests { @Autowired private JobDao jobDao; @Autowired private SessionFactory sessionFactory; @Autowired private UserService userService; @Autowired private PrinterService printerService; ... @Test public void saveJob_JobAdvancedToAssigned_AllExpectedStateChanges() { //Get an unassigned Job Job job = this.jobDao.getJob(-3L); assertEquals(JobState.UNASSIGNED, job.getCurrentState()); Date advancedToUnassigned = new GregorianCalendar(1998, 10, 30, 8, 31, 17).getTime(); assertEquals(advancedToUnassigned, job.getStateChange(JobState.UNASSIGNED).getDate()); //Satisfy advancement constraints and advance job.setPrinter(this.printerService.getPrinter(-1L)); Date advancedToAssigned = new Date(); job.advanceState( this.userService.getUserByUsername("admin"), advancedToAssigned); assertEquals(JobState.ASSIGNED, job.getCurrentState()); assertEquals(advancedToUnassigned, job.getStateChange(JobState.UNASSIGNED).getDate()); assertEquals(advancedToAssigned, job.getStateChange(JobState.ASSIGNED).getDate()); //Persist to DB this.sessionFactory.getCurrentSession().flush(); ... } ... } The error thrown is SQLCODE=-803, SQLSTATE=23505: could not insert collection rows: [jaci.model.job.Job.stateChanges#-3] org.hibernate.exception.ConstraintViolationException: could not insert collection rows: [jaci.model.job.Job.stateChanges#-3] at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:94) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.persister.collection.AbstractCollectionPersister.insertRows(AbstractCollectionPersister.java:1416) at org.hibernate.action.CollectionUpdateAction.execute(CollectionUpdateAction.java:86) at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:263) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:170) at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027) at jaci.dao.JobDaoIntegrationTest.saveJob_JobAdvancedToAssigned_AllExpectedStateChanges(JobDaoIntegrationTest.java:98) at org.springframework.test.context.junit4.SpringTestMethod.invoke(SpringTestMethod.java:160) at org.springframework.test.context.junit4.SpringMethodRoadie.runTestMethod(SpringMethodRoadie.java:233) at org.springframework.test.context.junit4.SpringMethodRoadie$RunBeforesThenTestThenAfters.run(SpringMethodRoadie.java:333) at org.springframework.test.context.junit4.SpringMethodRoadie.runWithRepetitions(SpringMethodRoadie.java:217) at org.springframework.test.context.junit4.SpringMethodRoadie.runTest(SpringMethodRoadie.java:197) at org.springframework.test.context.junit4.SpringMethodRoadie.run(SpringMethodRoadie.java:143) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(SpringJUnit4ClassRunner.java:160) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:97) Caused by: com.ibm.db2.jcc.b.lm: DB2 SQL Error: SQLCODE=-803, SQLSTATE=23505, SQLERRMC=1;ACI_APP.JOB_STATE, DRIVER=3.50.152 at com.ibm.db2.jcc.b.wc.a(wc.java:575) at com.ibm.db2.jcc.b.wc.a(wc.java:57) at com.ibm.db2.jcc.b.wc.a(wc.java:126) at com.ibm.db2.jcc.b.tk.b(tk.java:1593) at com.ibm.db2.jcc.b.tk.c(tk.java:1576) at com.ibm.db2.jcc.t4.db.k(db.java:353) at com.ibm.db2.jcc.t4.db.a(db.java:59) at com.ibm.db2.jcc.t4.t.a(t.java:50) at com.ibm.db2.jcc.t4.tb.b(tb.java:200) at com.ibm.db2.jcc.b.uk.Gb(uk.java:2355) at com.ibm.db2.jcc.b.uk.e(uk.java:3129) at com.ibm.db2.jcc.b.uk.zb(uk.java:568) at com.ibm.db2.jcc.b.uk.executeUpdate(uk.java:551) at org.hibernate.jdbc.NonBatchingBatcher.addToBatch(NonBatchingBatcher.java:46) at org.hibernate.persister.collection.AbstractCollectionPersister.insertRows(AbstractCollectionPersister.java:1389) Therein lies my problem… A nearly identical Class set (in fact, so identical that I've been chomping at the bit to make it a single class that serves both business entities) runs absolutely fine. It is identical except for name. Instead of Job it's Web. Instead of JobStateChange it's WebStateChange. Instead of JobState it's WebState. Both Job and Web's SortedSet of StateChanges are mapped as a Hibernate CollectionOfElements. Both are @Embeddable. Both are SortType.Natural. Both are backed by an Enumeration with some advancement rules in it. And yet when a nearly identical test is run for Web, no issue is discovered and the data flushes fine. For the sake of brevity I won't include all of the Web classes here, but I will include the test and if anyone wants to see the actual sources, I'll include them (just leave a comment). The data seed: insert into web (id, stock_type, pallet, pallet_id, date_received, first_icn, last_icn, shipment_id, current_state) values (-1, 'PF', '0011', 'A', '2008-12-31 08:30:02', '000000001', '000080000', -1, 'UNSTAGED'); insert into web_state (web_id, date, state, acting_user_id) values (-1, '2008-12-31 08:30:03', 'UNSTAGED', -1); The test: ... @ContextConfiguration(locations = { "/applicationContext-data.xml", "/applicationContext-service.xml" }) public class WebDaoIntegrationTest extends AbstractTransactionalJUnit4SpringContextTests { @Autowired private WebDao webDao; @Autowired private UserService userService; @Autowired private SessionFactory sessionFactory; ... @Test public void saveWeb_WebAdvancedToNewState_AllExpectedStateChanges() { Web web = this.webDao.getWeb(-1L); Date advancedToUnstaged = new GregorianCalendar(2008, 11, 31, 8, 30, 3).getTime(); assertEquals(WebState.UNSTAGED, web.getCurrentState()); assertEquals(advancedToUnstaged, web.getState(WebState.UNSTAGED).getDate()); Date advancedToStaged = new Date(); web.advanceState( this.userService.getUserByUsername("admin"), advancedToStaged); this.sessionFactory.getCurrentSession().flush(); web = this.webDao.getWeb(web.getId()); assertEquals( "Web should have moved to STAGED State.", WebState.STAGED, web.getCurrentState()); assertEquals(advancedToUnstaged, web.getState(WebState.UNSTAGED).getDate()); assertEquals(advancedToStaged, web.getState(WebState.STAGED).getDate()); assertNotNull(web.getState(WebState.UNSTAGED)); assertNotNull(web.getState(WebState.STAGED)); } ... } As you can see, I assert that the Web was reconstituted the way I expect, I advance it, flush it to the DB, and then re-get it and verify that the states are as I expect. Everything works perfectly. Not so with Job. A possibly pertinent detail: the reconstitution code works fine if I cease to map JobStateChange.data as a TIMESTAMP and instead as a DATE, and ensure that all of the StateChanges always occur on different Dates. The problem is that this particular business entity can go through many state changes in a single day and so it needs to be sorted by time stamp rather than by date. If I don't do this then I can't sort the StateChanges correctly. That being said, WebStateChange.date is also mapped as a TIMESTAMP and so I again remain absolutely befuddled as to where this error is arising from. I tried to do a fairly thorough job of giving all of the technical details of the implementation but as this particular question is very implementation specific, if I missed anything just let me know in the comments and I'll include it. Thanks so much for your help! UPDATE: Since it turns out to be important to the solution of my problem, I have to include the pertinent bits of the WebStateChange class as well. ... @Embeddable public class WebStateChange implements Comparable<WebStateChange> { @Temporal(TemporalType.TIMESTAMP) @Column(nullable = false) private Date date; @Enumerated(EnumType.STRING) @Column(nullable = false, length = WebState.FIELD_LENGTH) private WebState state; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "acting_user_id", nullable = false) private User actingUser; ... WebStateChange( final WebState state, final User actingUser, final Date date) { ExceptionUtils.illegalNullArgs(state, actingUser, date); this.state = state; this.actingUser = actingUser; this.date = new Date(date.getTime()); } @Override public int compareTo(final WebStateChange otherStateChange) { return this.date.compareTo(otherStateChange.date); } @Override public boolean equals(final Object candidate) { if (this == candidate) { return true; } else if (!(candidate instanceof WebStateChange)) { return false; } WebStateChange candidateWebState = (WebStateChange) candidate; return this.getState() == candidateWebState.getState() && this.getUser().equals(candidateWebState.getUser()) && this.getDate().equals(candidateWebState.getDate()); } @Override public int hashCode() { return this.getState().hashCode() + this.getUser().hashCode() + this.getDate().hashCode(); } ... }

    Read the article

  • Java/Spring: Why won't Spring use the validator object I have configured?

    - by GMK
    I'm writing a web app with Java & Spring 2.5.6 and using annotations for bean validation. I can get the basic annotation validation working fine, and Spring will even call a custom Validator declared with @Validator on the target bean. But it always instantiates a brand new Validator object to do it. This is bad because the new validator has none of the injected dependencies it needs to run, and so it throws a null pointer exception on validate. I need one of two things and I don't know how to do either. Convince Spring to use the validator I have already configured. Convince Spring to honor the @Autowired annotations when it creates the new validator. The validator has the @Component annotation, like this. @Component public class AccessCodeBeanValidator implements Validator { @Autowired private MessageSource messageSource; Spring finds the validator in the component scan, injects the autowired dependencies, but then ignores it and creates a new one at validation time. The only thing that I can do at the moment is add a validator reference into the controller for each validator object and use that ref directly, instead of relying on the bean validation framework to call the validator for me. It looks like this. // first validate via the annotations on the bean beanValidator.validate(accessCodeBean, result); // then validate using the specific validator class acbValidator.validate(accessCodeBean, result); if (result.hasErrors()) { If anyone knows how to convince spring to use the existing validator, instead of creating a new one, or how to make it do the autowiring when it creates a new one, I'd love to know.

    Read the article

  • Service injection into Controller (Spring MVC)

    - by ThaSaleni
    Hi I have a Spring web application, I have built it up to the controller stage and I could inject my Daos, into my Services fine. Now when I want to inject my Service into my controller i get an error for dependency with the Dao and further down the sessionFactory. I don't want to inject these again cause this will ultimately lead me to eventually create a data source but I have my Daos for data access and they already know about sessionFactory. Am I missing something here? here's the sample code snippets My Service: @Service("productService") @Transactional public class ProductServiceImpl implements ProductService { private ProductDao productDao; @Autowired public void setDao(ProductDao productDao) { this.productDao = productDao; } My Controller @Controller @WebServlet(name="controllerServlet", loadOnStartup= urlPatterns=...}) public class ControllerServlet extends HttpServlet { boolean isUserLogedIn =false; @Autowired private ProductService productService; public void setProductService(ProductService productService){ this.productService = productService; } Servlet-context Stack trace javax.servlet.ServletException: Servlet.init() for servlet mvcServlet threw exception org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98) org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999) org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java: 565) org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1812) java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) java.lang.Thread.run(Thread.java:662) root cause org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'controllerServlet': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.phumzile.acme.services.ProductService com.phumzile.acme.client.web.controller.ControllerServlet.productService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.phumzile.acme.services.ProductService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.p ostProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294) org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225) SERVLET-CONTEXT <context:component-scan base-package="com.phumzile.acme.client" /> <!-- Enables the Spring MVC @Controller programming model --> <mvc:annotation-driven /> </beans> APP-CONFIG <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>configuration.properties</value> </list> </property> </bean> <context:annotation-config/> <context:component-scan base-package="com.phumzile.acme" /> <import resource="db-config.xml" /> </beans> DB-CONFIG <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="idleConnectionTestPeriod" value="10800"/> <property name="maxIdleTime" value="21600"/> <property name="driverClass"> <value>${jdbc.driver.className}</value> </property> <property name="jdbcUrl"> <value>${jdbc.url}</value> </property> <property name="user"> <value>${jdbc.username}</value> </property> <property name="password"> <value>${jdbc.password}</value> </property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.a nnotation.AnnotationSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="annotatedClasses"> <list> <!-- Entities --> <value>com.phumzile.acme.model.User</value> <value>com.phumzile.acme.model.Person</value> <value>com.phumzile.acme.model.Company</value> <value>com.phumzile.acme.model.Product</value> <value>com.phumzile.acme.model.Game</value> <value>com.phumzile.acme.model.Book</value> <!-- Entities --> </list> </property> <property name="packagesToScan" value="com.phumzile.acme" /> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${jdbc.hibernate.dialect </prop> <prop key="hibernate.hbm2ddl.auto">validate</prop> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> <tx:annotation-driven /> </beans> CONFIGURATION.PROPERTIES jdbc.driver.className=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mydb jdbc.username=root jdbc.password=root jdbc.hibernate.dialect=org.hibernate.dialect.MySQLDialect

    Read the article

  • Why is the EntityManager in my GAE + Spring (+graniteds) project reset to null?

    - by prefabSOFT
    Hi all, I'm having a problem with autowiring my EntityManager. Actually at server startup I can see that the injection works ok, though when trying to use my EntityManager it appears to be null again. @Component public class DataDaoImpl { protected EntityManager entityManager; @Autowired public void setEntityManager(EntityManager entityManager) { System.out.println("Injecting "+entityManager); //works! this.entityManager = entityManager; } public void createData(String key, String value) { System.out.println("In createData entityManager is "+entityManager); //entityManager null!? ... Output: Injecting org.datanucleus.store.appengine.jpa.DatastoreEntityManager@a60d19 The server is running at http://localhost:8888/ In createData entityManager is null So somehow the autowired entityManager is reset to null when trying to use it. It's a graniteds powered project though I don't think this is graniteds related. Any ideas? Thanks a lot in advance, Jochen

    Read the article

  • java.lang.NullPointerException exception in my controller file (using Spring Hibernate Maven)

    - by mrjayviper
    The problem doesn't seemed to have anything to do with Hibernate. As I've commented the Hibernate stuff but I'm still getting it. If I comment out this line message = staffDAO.searchForStaff(search); in my controller file, it goes through ok. But I don't see anything wrong with searchForStaff function. It's a very simple function that just returns the string "test" and run system.out.println("test"). Can you please help? thanks But this is the error that I'm getting: SEVERE: Servlet.service() for servlet [spring] in context with path [/directorymaven] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause java.lang.NullPointerException at org.flinders.staffdirectory.controllers.SearchController.showSearchResults(SearchController.java:25) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:100) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:604) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:565) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778) at javax.servlet.http.HttpServlet.service(HttpServlet.java:621) at javax.servlet.http.HttpServlet.service(HttpServlet.java:728) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:931) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) at java.lang.Thread.run(Thread.java:722) My spring-servlet xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <context:component-scan base-package="org.flinders.staffdirectory.controllers" /> <mvc:annotation-driven /> <mvc:resources mapping="/resources/**" location="/resources/" /> <tx:annotation-driven /> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" p:location="/WEB-INF/spring.properties" /> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" /> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" p:dataSource-ref="dataSource" p:configLocation="${hibernate.config}" p:packagesToScan="org.flinders.staffdirectory"/> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" p:sessionFactory-ref="sessionFactory" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver" p:viewClass="org.springframework.web.servlet.view.tiles2.TilesView" /> <bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer" p:definitions="/WEB-INF/tiles.xml" /> <bean id="staffDAO" class="org.flinders.staffdirectory.dao.StaffDAO" p:sessionFactory-ref="sessionFactory" /> <!-- <bean id="staffService" class="org.flinders.staffdirectory.services.StaffServiceImpl" p:staffDAO-ref="staffDAO" />--> </beans> This is my controller file package org.flinders.staffdirectory.controllers; import java.util.List; //import org.flinders.staffdirectory.models.database.SearchResult; import org.flinders.staffdirectory.models.misc.Search; import org.flinders.staffdirectory.dao.StaffDAO; //import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class SearchController { //@Autowired private StaffDAO staffDAO; private String message; @RequestMapping("/SearchStaff") public ModelAndView showSearchResults(@ModelAttribute Search search) { //List<SearchResult> searchResults = message = staffDAO.searchForStaff(search); //System.out.println(search.getSurname()); return new ModelAndView("search/SearchForm", "Search", new Search()); //return new ModelAndView("search/SearchResults", "searchResults", searchResults); } @RequestMapping("/SearchForm") public ModelAndView showSearchForm() { return new ModelAndView("search/SearchForm", "search", new Search()); } } my dao class package org.flinders.staffdirectory.dao; import java.util.List; import org.hibernate.SessionFactory; //import org.springframework.beans.factory.annotation.Autowired; import org.flinders.staffdirectory.models.database.SearchResult; import org.flinders.staffdirectory.models.misc.Search; public class StaffDAO { //@Autowired private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public String searchForStaff(Search search) { /*String SQL = "select distinct telsumm_id as id, telsumm_parent_id as parentId, telsumm_name_title as title, (case when substr(telsumm_surname, length(telsumm_surname) - 1, 1) = ',' then substr(telsumm_surname, 1, length(telsumm_surname) - 1) else telsumm_surname end) as surname, telsumm_preferred_name as firstname, nvl(telsumm_tele_number, '-') as telephoneNumber, nvl(telsumm_role, '-') as role, telsumm_display_department as department, lower(telsumm_entity_type) as entityType from teldirt.teld_summary where (telsumm_search_surname is not null) and not (nvl(telsumm_tele_directory,'xxx') IN ('N','S','D')) and not (telsumm_tele_number IS NULL AND telsumm_alias IS NULL) and (telsumm_alias_list = 'Y' OR (telsumm_tele_directory IN ('A','B'))) and ((nvl(telsumm_system_id_end,sysdate+1) > SYSDATE and telsumm_entity_type = 'P') or (telsumm_entity_type = 'N')) and (telsumm_search_department NOT like 'SPONSOR%')"; if (search.getSurname().length() > 0) { SQL += " and (telsumm_search_surname like '" + search.getSurname().toUpperCase() + "%')"; } if (search.getSurnameLike().length() > 0) { SQL += " and (telsumm_search_soundex like soundex(('%" + search.getSurnameLike().toUpperCase() + "%'))"; } if (search.getFirstname().length() > 0) { SQL += " and (telsumm_search_preferred_name like '" + search.getFirstname().toUpperCase() + "%' or telsumm_search_first_name like '" + search.getFirstname() + "%')"; } if (search.getTelephoneNumber().length() > 0) { SQL += " and (telsumm_tele_number like '" + search.getTelephoneNumber() + "%')"; } if (search.getDepartment().length() > 0) { SQL += " and (telsumm_search_department like '" + search.getDepartment().toUpperCase() + "%')"; } if (search.getRole().length() > 0) { SQL += " and (telsumm_search_role like '" + search.getRole().toUpperCase() + "%')"; } SQL += " order by surname, firstname"; List<Object[]> list = (List<Object[]>) sessionFactory.getCurrentSession().createQuery(SQL).list(); for(int j=0;j<list.size();j++){ Object [] obj= (Object[])list.get(j); for(int i=0;i<obj.length;i++) System.out.println(obj[i]); }*/ System.out.println("test"); return "test"; } }

    Read the article

  • Is Inheritance in Struts2 Model-Driven Action possible?

    - by mryan
    Hello, I have a Model-Driven Struts2 action that provides correct JSON response. When I re-structure the action I get an empty JSON response back. Has anyone got inheritance working with Struts2 Model-Driven actions? Ive tried explicitly setting include properties in struts config: <result name="json" type="json"> <param name="includeProperties"> jsonResponse </param> </result> Code for all actions below - not actual code in use - I have edited and stripped down for clarity. Thanks in advance. Action providing correct response: public class Bike extends ActionSupport implements ModelDriven, Preparable { @Autowired private Service bikeService; private JsonResponse jsonResponse; private com.ets.model.Vehicle bike; private int id; public Bike() { jsonResponse = new JsonResponse("Bike"); } @Override public void prepare() throws Exception { if (id == 0) { bike = new com.ets.model.Bike(); } else { bike = bikeService.find(id); } } @Override public Object getModel() { return bike; } public void setId(int id) { this.id = id; } public void setBikeService(@Qualifier("bikeService") Service bikeService) { this.bikeService = bikeService; } public JsonResponse getJsonResponse() { return jsonResponse; } public String delete() { try { bike.setDeleted(new Date(System.currentTimeMillis())); bikeService.updateOrSave(bike); jsonResponse.addActionedId(id); jsonResponse.setAction("delete"); jsonResponse.setValid(true); } catch (Exception exception) { jsonResponse.setMessage(exception.toString()); } return "json"; } } Re-structured Actions providing incorrect response: public abstract class Vehicle extends ActionSupport implements ModelDriven { @Autowired protected Service bikeService; @Autowired protected Service carService; protected JsonResponse jsonResponse; protected com.ets.model.Vehicle vehicle; protected int id; protected abstract Service service(); @Override public Object getModel() { return bike; } public void setId(int id) { this.id = id; } public void setBikeService(@Qualifier("bikeService") Service bikeService) { this.bikeService = bikeService; } public void setCarService(@Qualifier("carService") Service carService) { this.carService = carService; } public JsonResponse getJsonResponse() { return jsonResponse; } public String delete() { try { vehicle.setDeleted(new Date(System.currentTimeMillis())); service().updateOrSave(vehicle); jsonResponse.addActionedId(id); jsonResponse.setAction("delete"); jsonResponse.setValid(true); } catch (Exception exception) { jsonResponse.setMessage(exception.toString()); } return "json"; } } public class Bike extends Vehicle implements Preparable { public Bike() { jsonResponse = new JsonResponse("Bike"); } @Override public void prepare() throws Exception { if (id == 0) { vehicle = new com.ets.model.Bike(); } else { vehicle = bikeService.find(id); } } @Override protected Service service() { return bikeService; } } public class Car extends Vehicle implements Preparable { public Car() { jsonResponse = new JsonResponse("Car"); } @Override public void prepare() throws Exception { if (id == 0) { vehicle = new com.ets.model.Car(); } else { vehicle = carService.find(id); } } @Override protected Service service() { return carService; } }

    Read the article

1 2 3 4  | Next Page >