I am using spring. I need to return object based on the String. I have below code.
public class DaoFactoryImpl implements DaoFactory {
private String dbType;
private OrganizationActions organizationActions;
private ProductActions productActions;
public void setOrganizationActions(OrganizationActions org){
this.organizationActions = org;
}
public void setProductActions(ProductActions prodActions){
this.productActions = prodActions;
}
public void setDbType(String dbType){
this.dbType = dbType;
}
#Override
public OrganizationActions getDaoObject() {
if(dbType.equalsIgnoreCase("Oracle")){
return organizationActions;
}else if(dbType.equalsIgnoreCase("DB2")){
return productActions;
}
return null;
}
}
Spring_congig.xml:
<util:properties id="configProps"
location="classpath:config/config.properties" />
<bean id="orgService" class="com.sample.OrganizationMongoService">
</bean>
<bean id="productService" class="com.sample.ProductMongoService"/>
<bean id="daoFactory" class="com.sample.factory.DaoFactoryImpl">
<property name="dbType" value="${dbName}"/>
<property name="organizationActions" ref="orgService"/>
<property name="productActions" ref="productService"/>
</bean>
I specify dbName in config.properties file. I have hard coded the same dbName (Oracle, DB2) in DaoFactoryImpl class. How can I avoid hard coding Oracle, DB2 in the code. Is there anyway to specify this criteria in the spring xml file?
Try creating a map in your spring config and use it to look up the correct instance. For example:
<bean id="daoFactory" class="com.sample.factory.DaoFactoryImpl">
<property name="dbType" value="${dbName}"/>
<property name="typeMap">
<map>
<entry key="Oracle" value-ref="orgService"/>
<entry key="DB2" value-ref="productService"/>
</map>
<property>
</bean>
Then do a lookup in your factory method:
public void setTypeMap(Map<String,Actions> typeMap){
this.typeMap = typeMap;
}
#Override
public OrganizationActions getDaoObject() {
return typeMap.get(dbType);
}
You can add the below code in Spring_congig.xml:-
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>properties/database.properties</value>
</property>
</bean>
and define your key-value pair in database.properties as:-
dbName=Oracle
Your Spring_congig.xml will pick up the required value for the given key.
<property name="dbType" value="${dbName}"/>
Related
public enum TypeEnum {
TYPE1, TYPE2, TYPE3;
}
public class Resources {
List<String> suppliers;
EnumMap<TypeEnum, String> items;
//setter and getter
}
I'm in the process of replicating the above bean in spring config xml file. I'm trying as per below but struck up with EnumMap. I understand that we can try using util:map. Please help.
<bean name="products" class="com.company.xxxx.Resources">
<property name="suppliers">
<list>
<value>suppliers1</value>
<value>suppliers2</value>
<value>suppliers3</value>
</list>
</property>
//TODO
<util:map id="items" >
</util:map>
</bean>
I am introducing Apache Ignite in our application as cache system as well as for computation. I have configured spring application using following configuration class.
#Configuration
#EnableCaching
public class IgniteConfig {
#Value("${ignite.config.path}")
private String ignitePath;
#Bean(name="cacheManager")
public SpringCacheManager cacheManager(){
SpringCacheManager springCacheManager = new SpringCacheManager();
springCacheManager.setConfigurationPath(ignitePath);
return springCacheManager;
}
}
Using it like
#Override
#Cacheable("cache1")
public List<Channel> getAllChannels(){
List<Channel> list = new ArrayList<Channel>();
Channel c1 = new Channel("1",1);
Channel c2 = new Channel("2",2);
Channel c3 = new Channel("3",3);
Channel c4 = new Channel("4",4);
list.add(c1);
list.add(c2);
list.add(c3);
list.add(c4);
return list;
}
Now I want to add write-through and read-through feature. I could not find any documentation to connect ignite to mongo.
The idea is not to talk to db directly but through ignite using write behind feature.
EDIT-----------------------
As suggested I implemented
public class ChannelCacheStore extends CacheStoreAdapter<Long, Channel> implements Serializable {
#Override
public Channel load(Long key) throws CacheLoaderException {
return getChannelDao().findOne(Channel.mongoChannelCode, key);
}
#Override
public void write(Cache.Entry<? extends Long, ? extends Channel> entry) throws CacheWriterException {
getChannelDao().save(entry.getValue());
}
#Override
public void delete(Object key) throws CacheWriterException {
throw new UnsupportedOperationException("Delete not supported");
}
private ChannelDao getChannelDao(){
return SpringContextUtil.getApplicationContext().getBean(ChannelDao.class);
}
}
And added this CacheStore into cache configuration like below :
<property name="cacheConfiguration">
<list>
<bean class="org.apache.ignite.configuration.CacheConfiguration">
<property name="name" value="channelCache"/>
<property name="cacheMode" value="PARTITIONED"/>
<property name="atomicityMode" value="ATOMIC"/>
<property name="backups" value="1"/>
<property name="readThrough" value="true"/>
<!-- Sets flag indicating whether write to database is enabled. -->
<property name="writeThrough" value="true"/>
<!-- Enable database batching. -->
<!-- Sets flag indicating whether write-behind is enabled. -->
<property name="writeBehindEnabled" value="true"/>
<property name="cacheStoreFactory">
<bean class="javax.cache.configuration.FactoryBuilder$SingletonFactory">
<constructor-arg>
<bean class="in.per.amt.ignite.cache.ChannelCacheStore"></bean>
</constructor-arg>
</bean>
</property>
</bean>
</list>
</property>
But now getting class cast exception
java.lang.ClassCastException: org.springframework.cache.interceptor.SimpleKey cannot be cast to java.lang.Long
at in.per.amt.ignite.cache.ChannelCacheStore.load(ChannelCacheStore.java:19)
You can have any kind of backing database by implementing CacheStore interface:
https://apacheignite.readme.io/docs/persistent-store
Have you tried setting your key generator?
#CacheConfig(cacheNames = "cache1",keyGenerator = "simpleKeyGenerator")
https://github.com/spring-projects/spring-boot/issues/3625
So in the below line of code from what you have shared,
#Cacheable("cache1")
public List<Channel> getAllChannels(){
the #Cacheable annotation is being used on a method which is not accepting any parameters. Spring cache uses the parameters (if in basic data type) as a key for the cache (response obj as the value). I believe this makes the caching ineffective.
I have an object returned from item processor.
public class PcdRateMapper
{
private Pcdrate pcdRate;
private Boolean isValidPcdRate;
public PcdRateMapper ()
{
// pcdRate = new Pcdrate ();
}
public Pcdrate getPcdRate ()
{
return pcdRate;
}
public void setPcdRate (Pcdrate pcdRate)
{
this.pcdRate = pcdRate;
}
public Boolean getIsValidPcdRate ()
{
return isValidPcdRate;
}
public void setIsValidPcdRate (Boolean isValidPcdRate)
{
this.isValidPcdRate = isValidPcdRate;
}
Now i want to extract only Pcdrate object values in my item writer. How can I do this. Currently I'm using following spring configuration but getting invalid property exception. Thanks in advance.
<
property name="lineAggregator">
<bean
class="org.springframework.batch.item.file.transform.DelimitedLineAggregator">
<property name="delimiter" value="," />
<property name=""></property>
<property name="fieldExtractor">
<bean
class="org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor">
<property name=""></property>
<property name="names"
value="company, subcoy" />
</bean>
</property>
</bean>
</property>
The invalid property exception may stem from
<property name=""></property>
where the property name is an empty string. You have that twice in the code above, remove it.
Your xml structure seems to be invalid, see spring_bean_definition
to see how it should look like.
On the bean of type BeanWrapperFieldExtractor you must set the property 'names' to the names of properties that you want to extraxt, in your case 'pcdRate'.
It should be configured like this :
<bean class="org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor">
<property name="names" value="pcdRate" />
</bean>
How to Set the argument value for a TreeSet in Spring?
public class Trainer {
String name;
TreeSet<String> batches;
public Trainer(String name, TreeSet<String> batches) {
super();
this.name = name;
this.batches = batches;
}
#Override
public String toString() {
StringBuilder x=new StringBuilder();
x.append("trainer:").append(name).append("\n");
x.append("batches:\n");
for(String a :batches)
{
x.append(a).append("\n");
}
return x.toString();
}
}
//here is the configuration file
<beans>
<bean id="abc" class="Trainer">
<constructor-arg value="asfsad"/>
<constructor-arg>
<set>
<value>kasdaskdnas</value>
<value>sjbdlsas;dkas</value>
</set>
</constructor-arg>
</bean>
</beans>
This throws an exception when trying to Create a object for it,could not convert constructor argument value of type [java.util.LinkedHashSet] to required type [java.util.TreeSet]:
You can use the util:set tag
<beans>
<bean id="abc" class="Trainer">
<constructor-arg value="asfsad" />
<constructor-arg>
<util:set set-class="java.util.TreeSet">
<value>kasdaskdnas</value>
<value>sjbdlsas;dkas</value>
</util:set>
</constructor-arg>
</bean>
</beans>
You can control the implementation of Set to be used for your Sring-managed set using the set-class attribute.
Something like this: <set set-class="java.util.TreeSet">
I have this factory interface
class TableManagerFactory {
TableManager getManager(Table table);
}
and current implementation lookups for a custom bean manager implementation or fall to a default one:
class TableManagerFactoryImpl implements TableManagerFactory {
public TableManager getManager(Table table) {
String beanName = table.getTableCode() + "Manager";
// Check for custom bean
if(!beanFactory.containsBean(beanName)) {
// Use default bean
beanName = "defaultTableManager";
}
return beanFactory.getBean(beanName);
}
Now I want to use ServiceLocatorFactoryBean based on a properties file like:
Table1=Table1Manager
Table2=AnotherTableManager
*=defaultTableManager
I have 2 problems:
In ServiceLocatorFactoryBean$ServiceLocatorInvocationHandler.tryGetBeanName()
because this method just perform a lookup using Properties.getProperty().
Table.toString() return a complex string (like "Table (tableCode) with columns...") and should be parsed to extract the tableCode
I found a not-so-easy solution based on Spring-AOP
<bean id="RegexServiceLocatorFactoryBeanStrategy_Pointcut" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
<property name="mappedName" value="getProperty" />
<property name="advice">
...
</advice>
</bean>
<bean id="TableManagerFactory_ServiceLocatorProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="properties">
<props>
<prop key="Table1">Table1Manager</prop>
<prop key="Table2">AnotherTableManager</prop>
<prop key="*">defaultTableManager</prop>
</props>
</property>
</bean>
<bean name="tableManagerFactory" class="org.springframework.beans.factory.config.ServiceLocatorFactoryBean">
<property name="serviceLocatorInterface" value="application.service.TableManagerFactory" />
<property name="serviceMappings">
<bean class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="targetName" value="TableManagerFactory_ServiceLocatorProperties" />
<property name="targetClass" value="java.util.Properties" />
<property name="autodetectInterfaces" value="false" />
<property name="interfaces"><list /></property>
<property name="interceptorNames">
<value>RegexServiceLocatorFactoryBeanStrategy_Pointcut</value>
</property>
</bean>
</property>
</bean>
I wrote a complex advice a la CacheAspectSupport and one Interceptor as:
class PropertiesWithRegexInterceptor implements MethodInterceptor {
#Override
public Object invoke(MethodInvocation m) throws Throwable {
final String v = (String) m.getArguments()[0];
final Object r = transformKey(v);
if(PROCEED != r) {
m.getArguments()[0] = r;
}
return m.proceed();
}
}
I want to make advice configuration easy (and xml-based as much as possible) writing less code as possible.
I'm using Spring 2.
Any suggestions? Thanks in advance.