I have the following code snippet that I was trying to fix:
In a spring context file, there is a bean configuration, something like this:
<bean id="myBean" >
<property name="interface">
<value>com.company.data.DataClass</value>
</property>
</bean>
With a corresponding setter as follows:
public void setInterface(Class<?>[] interfaces)
{
this.worker.setInterfaces(interfaces);
}
This works when the class exists.
But in certain environments the class may not exist and then an error is thrown.
Instead we'd like to handle the error when the Class isn't available.
I tried to fix the setter code as follows, but now it fails now when the Class actually does exist:
java.lang.ClassCastException: java.lang.String cannot be cast to [Ljava.lang.Class
public void setInterface(Object interfaceTest)
{
try
{
Class<?>[] interfaces = (Class<?>[])interfaceTest);
this.worker.setInterfaces(interfaces);
}
catch(Exception ex)
{
this.notValidInterface = true;
}
}
I'm not sure why the handling here is different.
Use String to define the value and Class.forName() to attempt to load the class checking if it exists.
<bean id="myBean">
<property name="interface">
<value>com.company.data.DataClass</value>
</property>
</bean>
public void setInterface(String[] interfaces) {
List<Class<?>> cls = new ArrayList<>();
for (String i : interfaces) {
try {
cls.add(Class.forName(i));
} catch (ClassNotFoundException ex) {
// handle the error
}
}
this.worker.setInterfaces(cls.toArray());
}
Related
I have the following bean:
package com.test;
#Component
public class Sample{
String modified = null;
#Value("${url}")
private String url;
public Sample(){
System.out.println(url );
if(baseUrl.equals(""){
throw new RuntimeException("missing");
}
else{
modified = "test"+url;
}
}
}
I have added:
<context:annotation-config />
<context:property-placeholder location="classpath:test.properties"/> & <context:component-scan base-package="com.test"/>
and trying to access above "modified" field as below
<bean id="url" class="java.lang.String">
<constructor-arg value="#{sample.modified}" />
</bean>
in my application context. But I keep getting the following error:
Field or property 'sample' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext'
Not sure why i get this error?
When Spring creates the object it uses the default constructor. It can't set the property until after it constructs it. Instead of what you have, try this to see if the value is being set.
#PostConstruct
public void init(){
System.out.println(url );
if(baseUrl.equals(""){
throw new RuntimeException("missing");
}
}
JustinKSU's answer is right. You have another option: inject value via constructor using #Autowired:
#Component
public class Sample {
#Autowired
public Sample(#Value("${url}") String url) {
System.out.println(url);
if(url.equals("") {
throw new RuntimeException("missing");
}
}
}
I have multiple provider classes (Provider1 and Provider2), how do I decide what bean I use depending on the input parameter in the Processor class?
public class Processor{
private Provider provider;
public void process(String providerName) throws Exception {
// What should I do here to invoke either provider1 or provider2 depending on the providerName?
provider.doOperation();
}
}
public class Provider1 {
public void doOperation(Exchange exchange) throws Exception {
//Code
}
}
public class Provider2 {
public void doOperation(Exchange exchange) throws Exception {
//Code
}
}
This is the case of Factory pattern. You can create a (ProviderFactory) class, register all the providers and get provider based on value, e.g.:
class ProviderFactory(){
private List<Provider> providers = new ArrayList<>();
public Provider getProvider(String input){
if(input.equals("test1")){
//Find based on criteria
return provider1;
}else if(input.equals("test2")){
//Find based on criteria
return provider2;
}
}
public void registerProvider(Provider provider){
providers.add(provider);
}
}
You can call registerProvider method on application startup and add as many providers as you want. Once that is initialised, you can call getProvider method and return appropriate instance based on some criteria.
Please note that providers doesn't necessarily need to be a list, it can be any data structure. It depends on which structure suits your criteria the best.
Here's documentation/more examples for Factory pattern.
What about somthing like this?
1# into your processor class :
public class Processor{
private Map<Provider> providers;
public void process(String providerName) throws Exception {
Provider provider = providers.get(providerName);
provider.doOperation();
}
}
2# in your spring config:
<bean id="provider1" class="xx.yy.zz.Provider1"/>
<bean id="provider2" class="xx.yy.zz.Provider2"/>
<bean id="processor" class="xx.yy.zz.Processor">
<property name="providers">
<map>
<entry key="provider1" value-ref="provider1" />
<entry key="provider2" value-ref="provider2" />
</map>
</property>
</bean>
now for example if you call processor.process("provider1") it will call provider1.doOperation()
I want to be able to store a Set of fully qualified Class names as a property of a Node. Given this Node:
#NodeEntity
public TestNode {
Set<Class<?>> classSet;
//getters and setters here
}
And the following custom converters:
public class ClassToStringConverter implements Converter<Class<?>, String> {
#Override
public String convert(final Class<?> source) {
return source.getName();
}
}
public class StringToClassConverter implements Converter<String, Class<?>> {
#Override
public String convert(final String source) {
Class<?> returnVal = null;
try {
returnVal = Class.forName(source);
} catch (ClassNotFoundException e) { }
return returnVal;
}
}
I register the converters with Spring context as such:
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="my.package.ClassToStringConverter"/>
<bean class="my.package.StringToClassConverter "/>
</set>
</property>
</bean>
Then using my repository, I can properly save and retrieve the Node, and it stores the fully qualified class name as expected using my custom converters. However, I would like to be able to query by a Class name as such in my repository:
#Query("MATCH (m:TestNode) where {0} in m.classSet return m;")
public findByClassInClassSet(Class<?> clazz);
However, this seems to convert the Class using Class.toString() instead of using my Converter. So it is searching for the String "class my.package.TestNode" instead of what the Converter correctly stored as "my.package.TestNode".
Am I missing something here or doing something wrong? How can I benefit from these converters if I can't query using the Class type?
NOTE: Please excuse any typos - this code is on a disconnected network so I couldn't copy paste. If there are any typos, I assure you that is not the problem on my actual code.
Should be fixed in the next milestone release for derived finders.
For your annotated query-method, SDN cannot know what you are referring to with your parameter, so it will not be able to convert it, ever.
I am wondering how to implement batch operations with my insert statements using MyBatis 3 & Spring 3?
For example, here is what is currently being done:
spring.xml:
<bean id="jndiTemplateDatasource" class="org.springframework.jndi.JndiTemplate">
<property name="environment">
<props>
<prop key="java.naming.factory.initial">${context.factory}</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiTemplate" ref="jndiTemplateDatasource"/>
<property name="jndiName" value="${connectionpool.jndi}"/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.test" />
</bean>
MyService.xml:
<insert id="insertMyRecord" parameterType="com.test.MyRecord" >
insert into ... // code removed
</insert>
MyService.java:
public interface MyService {
public void insertMyRecord (MyRecord);
}
MyController.java:
#Controller
public class MyController {
#Autowired
private MyService myService;
#Transactional
#RequestMapping( .... )
public void bulkUpload (#RequestBody List<MyRecord> myRecords) {
for (MyRecord record : myRecords) {
myService.insertMyRecord(record);
}
}
}
Disclaimer: That is just pseudo code for demonstration purposes
So what can I do to turn that into a batch process?
Ideally I want to be able to do it with least "intrusion" into code, i.e. use annotations more preferred, but if not possible what is the next best thing?
Also, this needs to be configured just for this one service, not for everything in the project.
The accepted answer above doesn't actually get you batch mode for MyBatis. You need to choose the proper Executor via ExecutorType.BATCH. That is either passed as a parameter to SqlSession.openSession in standard MyBatis API or, if using MyBatis-Spring, as an option to the SqlSessionTemplate. That is done via:
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
<constructor-arg index="1" value="BATCH" />
</bean>
There is nothing else that needs to be done.
This is running and tested example ...
Update multiple rows using batch (ibatis + java )
In this ex. I am updating attending count from table with respective to partyid.
public static int updateBatch(List<MyModel> attendingUsrList) {
SqlSession session = ConnectionBuilderAction.getSqlSession();
PartyDao partyDao = session.getMapper(PartyDao.class);
try {
if (attendingUsrList.size() > 0) {
partyDao.updateAttendingCountForParties(attendingUsrList);
}
session.commit();
} catch (Throwable t) {
session.rollback();
logger.error("Exception occurred during updateBatch : ", t);
throw new PersistenceException(t);
} finally {
session.close();
}
}
Model class where variable is defined :
public class MyModel {
private long attending_count;
private String eid;
public String getEid() {
return eid;
}
public void setEid(String eid) {
this.eid = eid;
}
public long getAttending_count() {
return attending_count;
}
public void setAttending_count(long attending_count) {
this.attending_count = attending_count;
}
}
party.xml code
Actual query where batch execute
<foreach collection="attendingUsrList" item="model" separator=";">
UPDATE parties SET attending_user_count = #{model.attending_count}
WHERE fb_party_id = #{model.eid}
</foreach>
Interface code here
public interface PartyDao {
int updateAttendingCountForParties (#Param("attendingUsrList") List<FBEventModel>attendingUsrList);
}
Here is my batch session code
public static synchronized SqlSession getSqlBatchSession() {
ConnectionBuilderAction connection = new ConnectionBuilderAction();
sf = connection.getConnection();
SqlSession session = sf.openSession(ExecutorType.BATCH);
return session;
}
SqlSession session = ConnectionBuilderAction.getSqlSession();
I'm not sure I understand the question fully correct but I will try to give you my thoughts.
For making the single service I would recommend to generify the service interface:
public void bulkUpload (#RequestBody List<T> myRecords)
Then you can check the type of the object and call the propper mapper repository.
Then you can generify it more by creating a common interface:
public interface Creator<T> {
void create(T object);
}
and extend it by your mapper interface:
public interface MyService extends Creator<MyRecord>{}
Now the most complicated step: you get the object of a particular type, see what exact mapper implements the Creator interface for this class (using java reflection API) and invoke the particular method.
Now I give you the code I use in one of my projects:
package com.mydomain.repository;
//imports ...
import org.reflections.Reflections;
#Repository(value = "dao")
public class MyBatisDao {
private static final Reflections REFLECTIONS = new Reflections("com.mydomain");
#Autowired
public SqlSessionManager sqlSessionManager;
public void create(Object o) {
Creator creator = getSpecialMapper(Creator.class, o);
creator.create(o);
}
// other CRUD methods
#SuppressWarnings("unchecked")
private <T> T getSpecialMapper(Class<T> specialClass, Object parameterObject) {
Class parameterClass = parameterObject.getClass();
Class<T> mapperClass = getSubInterfaceParametrizedWith(specialClass, parameterClass);
return sqlSessionManager.getMapper(mapperClass);
}
private static <T, P> Class<? extends T> getSubInterfaceParametrizedWith(Class<T> superInterface, Class<P> parameterType) {
Set<Class<? extends T>> subInterfaces = REFLECTIONS.getSubTypesOf(superInterface);
for (Class<? extends T> subInterface: subInterfaces) {
for (Type genericInterface : subInterface.getGenericInterfaces()) {
if (!(genericInterface instanceof ParameterizedType)) continue;
ParameterizedType parameterizedType = (ParameterizedType) genericInterface;
Type rawType = parameterizedType.getRawType();
if (rawType instanceof Class<?> && ((Class<?>) rawType).isAssignableFrom(superInterface)) {
for (Type type: parameterizedType.getActualTypeArguments()) {
if (type instanceof Class<?> && ((Class<?>) type).isAssignableFrom(parameterType)) {
return subInterface;
}
}
}
}
}
throw new IllegalStateException(String.format("No extension of %s found for parametrized type %s ", superInterface, parameterType));
}
}
Warning! This approach can have bad performance impact so use it in non-performance-critical actions
If you want bulk insert I would recommend to use mybatis foreach for bulk insert as described here.
If you think you don't want to write sql for every type of objects you better use Hibernate or any other advanced ORM. MyBatis is just an SQL mapping interface.
I have a simple JFrame as the main window of my Java desktop application and I would like to configure it as a Spring bean. I would like to set properties, inject dependencies and launch it. Here's my frame class:
public class MainFrame extends JFrame {
public MainFrame() {
setTitle("Static Title");
setVisible(true);
}
}
My Spring application context:
<bean class="com.example.MainFrame">
<property name="title" value="Injected Title" />
</bean>
Then I fire it all up...
public static void main(String ... args) {
new ClassPathXmlApplicationContext("applicationContext.xml");
}
...which is followed by this java.beans.IntrospectionException:
type mismatch between indexed and non-indexed methods: location
The frame is actually displayed but there's that exception and the title remains "Static Title". So I have a few questions...
I've seen this being done by IBM in a 2005 tutorial but with Spring 1.2, and I don't even know what JRE. So how do I approach this exception? Is it possible to configure a JFrame as a Spring bean or do I need to proxy it or something?
I'm also wary of not launching the application from the event dispatching thread. So if there's a cleaner way of doing this I'd like to know about it. I can easily dispatch everything except that I don't know how to dispatch the construction itself.
Finally feel free to criticise the overall concept. I haven't come across many examples of Spring managed Swing applications. I'm using Spring-3.1 with Java-1.6.
Thanks.
I'm having the same problem, and it seems that's actually a bug on Spring:
https://jira.springsource.org/browse/SPR-8491
I think I'll wrap a FactoryBean around the panel and see if it works. I'll edit this post later, in case it works (or not)
-- edit --
Okay, instantiating it through a FactoryBean does get around the problem. The declaration becomes a little awkward, but that will have to do, at least until the aforementioned bug is fixed.
package com.ats.jnfe.swing;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.BeanInstantiationException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.FactoryBean;
/**
* Contorna, em caráter temporário, o bug apontado em:
* https://jira.springsource.org/browse/SPR-8491
* Quando o erro acima for resolvido, esta classe estará obsoleta.
*
* #author HaroldoOliveira
*/
public class SwingFactoryBean<T> implements FactoryBean<T> {
private Class<T> beanClass;
private Map<String, Object> injection;
private String initMethod;
private Map<String, PropertyDescriptor> properties;
private BeanInfo beanInfo;
private Method initMethodRef;
public T getObject() throws Exception {
T t = this.getBeanClass().newInstance();
if (this.getInjection() != null) {
for (Map.Entry<String, Object> en : this.getInjection().entrySet()) {
try {
this.properties.get(en.getKey()).getWriteMethod()
.invoke(t, en.getValue());
} catch (Exception e) {
throw new BeanInitializationException(MessageFormat.format(
"Error initializing property {0} of class {1}",
en.getKey(), this.getBeanClass().getName()), e);
}
}
}
if (this.initMethodRef != null) {
this.initMethodRef.invoke(t);
}
return t;
}
public Class<?> getObjectType() {
return this.getBeanClass();
}
public boolean isSingleton() {
return false;
}
public void initialize() {
try {
this.beanInfo = Introspector.getBeanInfo(this.getBeanClass());
this.properties = new HashMap<String, PropertyDescriptor>();
PropertyDescriptor[] descriptors = this.beanInfo.getPropertyDescriptors();
for (PropertyDescriptor pd : descriptors) {
this.properties.put(pd.getName(), pd);
}
if (this.getInitMethod() != null) {
this.initMethodRef = this.getBeanClass()
.getMethod(this.getInitMethod());
}
} catch (Exception e) {
throw new BeanInitializationException(
"Error initializing SwingFactoryBean: " + e.getMessage(), e);
}
}
public Class<T> getBeanClass() {
if (this.beanClass == null) {
throw new BeanInitializationException("Class not informed.");
}
return this.beanClass;
}
public void setBeanClass(Class<T> beanClass) {
this.beanClass = beanClass;
}
public Map<String, Object> getInjection() {
return injection;
}
public void setInjection(Map<String, Object> injection) {
this.injection = injection;
}
public String getInitMethod() {
return initMethod;
}
public void setInitMethod(String initMethod) {
this.initMethod = initMethod;
}
}
Usage example:
<bean id="certificadoNFeConfiguracaoDialog" class="com.ats.jnfe.swing.SwingFactoryBean" init-method="initialize" scope="prototype" lazy-init="true">
<property name="beanClass" value="com.ats.ecf.view.swing.util.dialog.OKCancelDialog" />
<property name="initMethod" value="inicializa" />
<property name="injection">
<map>
<entry key="selector">
<bean class="com.ats.jnfe.swing.SwingFactoryBean" init-method="initialize">
<property name="beanClass" value="com.ats.jnfe.swing.CertificadoNFeConfigPanel" />
<property name="initMethod" value="inicializa" />
<property name="injection">
<map>
<entry key="fachada" value-ref="certificadoNFeConfiguracaoFacade" />
</map>
</property>
</bean>
</entry>
</map>
</property>
</bean>
Runs with Spring 3.0.7.RELEASE, 3.1.4.RELEASE und 3.2.3.RELEASE.
It seems it has been a bug as mentioned in another answer.
My thought would be to keep Swing out of Spring. Past anything trivial, wiring up a GUI using something else is going to be too tedious. Instead, I would change what you are doing and just use main() to create the Spring content and then create your GUI.
If all you are doing in Spring would be creating the MainFrame and starting it, maybe the easiest thing is to create a FactoryBean that creates the frame. The factory could also call setVisible() via a SwingUtilities.invokeLater() call.
Confirmed runs with Spring 4.0.2.RELEASE too.