Spring conversion strategy in getBean for JAXB setterless collection - spring

Question
How can I inject a bean containing a list generated by JAXB ?
Detail
These lists have no setters.
You populate them through
getMyList().getList().add(stuff);
For standard java Collections, you usually rely on spring-utils, but Spring does not support these JAXB lists.
Message: no matching editors or conversion strategy found
Context
WSDL-first - CXF server
mock responses are pulled from Spring Application context files
Hints
I'm reluctant to introduce a second JAXB runtime just for the sake of mock response, especially considering this will involve generating a slew of new classes to model my domain objects (i.e. thereby duplicating the objects generated by wsdl2java).

Try creating a Bean for the list:
<bean id="list" class="java.util.ArrayList">
<constructor-arg>
<list>
<ref bean="element1" />
<ref bean="element2" />
</list>
</constructor-arg>
</bean>
Then creating a bean for the inner class using the A$B syntax:
<bean id="myList" class="myPackage.MyOuterClass$MyList" >
<property name="list" ref="list" />
</bean>
Finally the OuterClass Bean:
<bean id="myOuterClass" class="myPackage.MyOuterClass" >
<property name="myList" ref="myList" />
</bean>

My Solution:
I ended up using eclipselink MOXy.
The choice of MOXy was driven by the following characteristics
MOXy allows to declare root elements outside of the classes generated by CXF. So that there is no need to interfere with these classes.
MOXy being a JAXB implementation has no problem dealing with the way JAXB populates lists (without setters).
Remarks:
MOXy XPath support is still weak. I needed to access a specific XML element (a response) out of the total XML file (the list of possible mock responses) and hoped I could unmarshal only a portion of this XML file based on an XPath predicate but this is not supported yet (in 2.5). Support is planned for 2.6.
I did not use any Spring JAXB front-end as a façade for MOXy, as my Mock SEI are already injected through Spring.
Using MOXy proved a pleasant experience and is quite easy to get started with.
I did not experience any collision between MOXy as a JAXB payload jar and the way CXF uses the JDK JAXB implementation for its SOAP layer.

Related

Using Spring Transactions in MyBatis API

We have developed a data persistence framework using Mybatis. The framework uses plain MyBatis APIs. (We were prohibited from using any mybatis-spring, do not ask… why?)
Now we have to integrate this persistence framework with another framework developed by other teams. This other framework heavily uses spring transactions for everything. Our persistent framework DAOs will be used by this framework within its own API ….that means the spring managed transactions will be propagated to MyBatis DAO. It is expected that our MyBatis based persistence framework should participate in spring managed transactions without any issues.
There are two options for us to make this work
(1)Change our persistent framework to use mybatis-spring module. Change DAOs to use mappers directly injected using spring and spring’s SqlSessionFactoryBean. I did build a small example simulating both the frameworks and everything works without any issue. The problem is with this approach that it requires changing almost all the DAOs to use spring injected mapper, extensively test the framework again. We simply do not have time available due to delivery timeline.
(2)Use mybatis-spring, define SqlSeeionFactory using spring – set the datasource and transaction manager used by other framework. Something like
<bean id="smpDataSource" class="oracle.jdbc.pool.OracleDataSource" destroy-method="close">
<property name="connectionCachingEnabled" value="true" />
<property name="URL"> <value>${db.thin.url}</value></property>
<property name="user"> <value>${db.user}</value></property>
<property name="password"><value>${db.password}</value>
</property>
</bean>
<bean id="dbTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="smpDataSource" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="smpDataSource" />
<property name="typeAliasesPackage" value="spike.smp51.domain" />
<property name="mapperLocations" value="classpath*:spike/smp51/mappers/*.xml" </bean>
Then in applicataion code MyBatis DAO gets the sqlseesionfactory from spring like
public static SqlSessionFactory getSqlSessionFactory() throws Exception
{
DefaultSqlSessionFactory sessionFactory = (DefaultSqlSessionFactory)ctx.getBean("sqlSessionFactory");
return sessionFactory;
}
All DAOs already use SqlSeesionFactory to open and close sessions. Just replace that mybatis created sqlseeionfactory with spring created sqlseeionfactory. That way we will have only few lines of changes.
This approach is outlined here
http://mybatis.github.io/spring/using-api.html
The mybatis documentation warns about this approach – specifically that it will not participate in spring transactions.
When I tried the 2nd approach, our framework was able to participate in spring transactions. This is strange. Is the MyBatis documentation incorrect then? I did verify it extensively by creating various transaction boundaries using spring transactions + AOP . MyBatis DAOs are able to participate in spring managed transactions every time. Since this second approach will save us 90% of the development time – we really like to use it – but worried since MyBatis warns following this approach. Has anyone tried this approach? Any feedback is greatly appreciated.
Did you have any return on that ?
I'm wondering if in the doc they're talking about org.apache.ibatis.session.SqlSessionFactory from Mybatis-api while the SqlSessionFactory you're using is from the mybatis-spring lib : org.mybatis.spring.SqlSessionFactoryBean

Spring does not autowire beans with JAX-WS webservice end points

I am trying to consume a JAX-WS webservice written by me. I always get nullPointerException for spring autowired annotated beans. However, everything works fine within serverSide over web, but accessing beans through JAX-WS webservice.
I have tried by extending SpringBeanAutowiringSupport, but still no luck. How can I do this.
regards, Rohit
I had no experience extending SpringBeanAutowiringSupport but had successfuly used this approach:
Annotate webService class such a way :
#Component("yourWebService")
#WebService(endpointInterface ="your.package.YourServicePort")
Create new spring-context xml for webService and define JAX-WS endpoint :
<jaxws:endpoint
id="yourServiceEndpoint"
implementor="#yourWebService"
address="${yourWebService.wsdl.url}"> //load url from properties file
</jaxws:endpoint>
I suppose you know how to use props in spring, but will explain just in case. You should also create yourWebService.properties file and define it in spring context to use this construction ${yourWebService.wsdl.url} :
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>yourWebService.properties</value>
</list>
</property>
Using this approach I had successfuly used JAX with Spring

Why is autowiring required? What is the explanation of the concept of autowiring?

Why is autowiring required? What is the explanation for the concept of autowiring?
#autowired annotation in Spring Framework.
Autowiring is not required, just convenient.
It means that if you have a property that requires an InterfaceA and a single bean has been declared in Spring that is of type InterfaceA, instead of using XML to manually "wire up" the relationship (setting a bean reference as a property of another), you can let Spring do the wiring for you.
This is a common question for the beginners. As the beans are injected using DI (setter injections, constructor injections), why do we need auto-wiring? Auto-wiring also doing the same thing, right?
The answer is, it saves you from writing more code.
If using an XML file, using autowire attribute saves you from writing the wiring code in the bean definition.
Please look at code below.
Configuration code without Auto-wiring:
<bean id="employee" class="com.Employee">
<property name="name" value="Dexter"></property>
</bean>
<bean id="employeeService" class="com.EmployeeService">
<property name="employee" ref="employee"></property>
</bean>
Configuration code with Auto-wiring:
<bean id="employee" class="com.Employee">
<property name="name" value="Dexter"></property>
</bean>
<bean id="employeeService" class="com.EmployeeService" autowire="byName" />
Note that we did not have to write anything to refer property of EmployeeService, i.e., Employee. But still it was injected. Autowiring makes the container to search the bean configurations and do the collaboration among beans, without the developer specifically mentioning these.
If we use annotation, even we don’t have to write anything in XML files, including this autoware="byName", etc. Simply #Autowired on bean's setter/field/constructor is sufficient.

Correct way to get transactions using Spring Data Neo4j's simple object/graph mapping?

I'm using the simple object/graph mapping in Spring Data Neo4j 2.0, where I perform persistence operations using the Spring Data repository framework. I'm working with the repositories rather than working with the Neo4jTemplate. I inject the repositories into my Spring Web MVC controllers, and the controllers call the repos directly. (No intermediate service layer--my operations are generally CRUDs and finder queries.)
When I do read operations, there are no issues. But when I do write operations, I get "NotInTransactionException". My understanding is that read ops in Neo4j don't require transactions, but write ops do.
What's the best way to get transactions into the picture here, assuming I want to stick with the simple OGM? I'm wanting to use #Transactional, but putting that on the various repository interfaces doesn't work. If I introduce an intermediate service tier in between the controllers and the repositories and then annotate the service beans with #Transactional, then it works, but I'm wondering whether there's a simpler way to do it. Without Spring Data, I'd typically have access to the DAO (repository) implementations, so I'd be able to annotate the concrete DAOs with #Transactional if I wanted to avoid a pass-through service tier. With Spring Data the repos are dynamically generated so that doesn't appear to be an option.
First, note that having transactional DAOs is not generally a good practice. But if you don't have a service layer, then let it be on the DAOs.
Then, you can enable declarative transactions. Here's how I did it:
First, define an annotation called #GraphTransactional:
#Retention(RetentionPolicy.RUNTIME)
#Transactional("neo4jTransactionManager")
public #interface GraphTransactional {
}
Update: spring-data-neo4j have added such an annotation, so you can reuse it instead of creating a new one: #Neo4jTransactional
Then, in applicationContext.xml, have the following (where neo4jdb is your EmbeddedGraphDatabase):
<bean id="neo4jTransactionManagerService"
class="org.neo4j.kernel.impl.transaction.SpringTransactionManager">
<constructor-arg ref="neo4jdb" />
</bean>
<bean id="neo4jUserTransactionService" class="org.neo4j.kernel.impl.transaction.UserTransactionImpl">
<constructor-arg ref="neo4jdb" />
</bean>
<bean id="neo4jTransactionManager"
class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManager" ref="neo4jTransactionManagerService" />
<property name="userTransaction" ref="neo4jUserTransactionService" />
</bean>
<tx:annotation-driven transaction-manager="neo4jTransactionManager" />
Have in mind that if you use another transaction manager as well, you'd have to specify order="2" for this annotation-driven definition, and also have in mind that you won't have two-phase commit if you have one method that is declared to be both sql and neo4j transactional.

What's the difference between <mvc:annotation-driven /> and <context:annotation-config /> in servlet?

I am migrating from Spring 2.5 to Spring 3.
They have introduced <mvc:annotation-driven /> which does some black magic. This is expected to be declared in servlet configuration file only.
In Spring 2.5 I have just used <context:annotation-config /> and <context:component-scan base='...'/> tags declared both in application-context.xml and dispatcher servlet configuration XML with appropriate base packages to scan.
So I wonder what is the difference between mvc:annotation-driven and context:annotation-config tags in servlet config and what can I eliminate in Spring 3 config files?
<context:annotation-config> declares support for general annotations such as #Required, #Autowired, #PostConstruct, and so on.
<mvc:annotation-driven /> declares explicit support for annotation-driven MVC controllers (i.e. #RequestMapping, #Controller, although support for those is the default behaviour), as well as adding support for declarative validation via #Valid and message body marshalling with #RequestBody/ResponseBody.
There is also some more detail on the use of <mvc:annotation-driven /> in the Spring docs. In a nutshell, <mvc:annotation-driven /> gives you greater control over the inner workings of Spring MVC. You don't need to use it unless you need one or more of the features outlined in the aforementioned section of the docs.
Also, there are other "annotation-driven" tags available to provide additional functionality in other Spring modules. For example, <transaction:annotation-driven /> enables the use of the #Transaction annotation, <task:annotation-driven /> is required for #Scheduled et al...
mvc:annotation-driven is a tag added in Spring 3.0 which does the following:
Configures the Spring 3 Type ConversionService (alternative to PropertyEditors)
Adds support for formatting Number fields with #NumberFormat
Adds support for formatting Date, Calendar, and Joda Time fields with #DateTimeFormat, if Joda Time is on the classpath
Adds support for validating #Controller inputs with #Valid, if a JSR-303 Provider is on the classpath
Adds support for support for reading and writing XML, if JAXB is on the classpath (HTTP message conversion with #RequestBody/#ResponseBody)
Adds support for reading and writing JSON, if Jackson is o n the classpath (along the same lines as #5)
context:annotation-config
Looks for annotations on beans in the same application context it is defined and declares support for all the general annotations like #Autowired, #Resource, #Required, #PostConstruct etc etc.

Resources