I was using spring to create objects through beans. Now I tried to use aop to create the same object and I get $Proxy cannot be cast to SaleRoom exception.
the previous xml was:
<?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:aop="http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"
xmlns:context="http://www.springframework.org/schema/context/spring-context-2.5.xsd"
xmlns:flow="http://www.springframework.org/schema/webflow-config/spring-webflow-config- 1.0.xsd"
xmlns:jm s="http://www.springframework.org/schema/jms/spring-jms-2.5.xsd"
xmlns:jee="http://www.springframework.org/schema/jee/spring-jee-2.5.xsd"
xmlns:lang="http://www.springframework.org/schema/lang/spring-lang-2.5.xsd"
xmlns:osgi="http://www.springframework.org/schema/osgi/spring-osgi.xsd"
xmlns:tx="http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"
xmlns:util="http://www.springframework.org/schema/util/spring-util-2.5.xsd"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/aop/spring-aop-2.5.xsd/spring-spring-aop-2.5.xsd-2.5.xsd
http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/context/spring-context-2.5.xsd/spring-spring-context-2.5.xsd-2.5.xsd
http://www.springframework.org/schema/webflow-config/spring-webflow-config-1.0.xsd http://www.springframework.org/schema/webflow-config/spring-webflow-config-1.0.xsd/spring-spring-webflow-config-1.0.xsd-2.5.xsd
http://www.springframework.org/schema/jms/spring-jms-2.5.xsd http://www.springframework.org/schema/jms/spring-jms-2.5.xsd/spring-spring-jms-2.5.xsd-2.5.xsd
http://www.springframework.org/schema/jee/spring-jee-2.5.xsd http://www.springframework.org/schema/jee/spring-jee-2.5.xsd/spring-spring-jee-2.5.xsd-2.5.xsd
http://www.springframework.org/schema/lang/spring-lang-2.5.xsd http://www.springframework.org/schema/lang/spring-lang-2.5.xsd/spring-spring-lang-2.5.xsd-2.5.xsd
http://www.springframework.org/schema/osgi/spring-osgi.xsd http://www.springframework.org/schema/osgi/spring-osgi.xsd/spring-spring-osgi.xsd-2.5.xsd
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/tx/spring-tx-2.5.xsd/spring-spring-tx-2.5.xsd-2.5.xsd
http://www.springframework.org/schema/util/spring-util-2.5.xsd http://www.springframework.org/schema/util/spring-util-2.5.xsd/spring-spring-util-2.5.xsd-2.5.xsd
">
<bean id="sale01" class="application.common.entities.BidRoom">
<property name="itemId" value="0001"/>
<property name="lifeTime" value="15"/>
</bean>
</beans>
And I used the following code to create the sales:
ApplicationContext context = new FileSystemXmlApplicationContext(SalesManager.getSalesSourceFile());
SaleRoom saleRoom;
List<String> salesNames = new LinkedList<String>();
List<SaleRoom> allSales = new LinkedList<SaleRoom>();
// Get all sales id's for beans
NodeList salesNodeList = salesDoc.getElementsByTagName("bean");
for (int i = 0; i < salesNodeList.getLength(); i++) {
Node nNode = salesNodeList.item(i);
salesNames.add(((Element) nNode).getAttribute("id").toString());
}
for (String saleName : salesNames) {
if(saleName.contains("sale")) {
saleRoom = (SaleRoom) context.getBean(saleName);
allSales.add(saleRoom);
}
}
return allSales;
This is the new 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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<aop:aspectj-autoproxy>
<aop:include name="logSettersCalls"/>
</aop:aspectj-autoproxy>
<bean id="logSettersCalls" class="application.logging.aop.LogSettersCalls"/>
<bean id="sale01" class="application.common.entities.BidRoom">
<constructor-arg index="0" type="int" value="0001"/>
<constructor-arg index="1" type="int" value="15"/>
</bean>
</beans>
The Aspect logging class:
#Aspect
public class LogSettersCalls {
#Pointcut("execution(void set*(*))")
public void setMethod() {}
#Before("setMethod()")
public void logSetterCall(JoinPoint theJoinPoint) {
String methodName = theJoinPoint.getSignature().getName();
Object newValue = theJoinPoint.getArgs()[0];
Object theObject = theJoinPoint.getTarget();
System.out.println("The method " + methodName + " is called on object "
+ theObject + " with the value " + newValue);
}
}
I'm using the same code for creating the beans via aop. and I get
Exception in thread "main" java.lang.ClassCastException: $Proxy11 cannot be cast to application.common.entities.SaleRoom
The line that throws the exception:
saleRoom = (SaleRoom) context.getBean(saleName);
Any help will be appreciated. Thanks.
Does your SaleRoom class implement some interface? If yes, then you should use interface and not class in you code:
ISaleRoom saleRoom = (ISaleRoom) context.getBean(saleName);
Because if your bean implements some interface then Spring by default will create proxy based on this interface.
Here is a good article about proxy creation in Spring.
Also you can change proxying mechanism for Spring AOP if you want to create proxy for target class. This is described here in reference documentation.
Related
I am new to spring. So I couldn't figure out what issue is there in the below code. I have two classes. I am defining a #Bean Channel and am autowiring that bean in the next class. I am using annotation for autowiring. When I try " System.out.println(externalChannel.toString());" am getting null values and the exception null pointer exception is thrown.
#Configuration
public class MessagingConfig
{
#Value("${service.name}")
private String queueName; // NOSONAR
#Value("${${user}")
private String schema;
#Value("${Owner}")
private String owner;
#Bean
public Channel externalChannel()
{
EventsProvider eventsProvider = new EventsProvider();
eventsProvider.setOwner(owner);
System.out.println("-------Cost And Events Channel-------"+eventsProvider.getEventsChannel());
return eventsProvider.getEventsChannel();
}
}
And Another class is
#Component
#LoggedService
#Monitored(useActualType = true)
public class MessagePublish {
#Autowired
private MessagingService messageService;
#Autowired
private Channel externalChannel;
public void publishTPSMessage(SourceTransaction sourceTransaction)
{
TPSEvent event = new TPSEvent(ContextHolder.getContextId(), new Date(), GuidUtils.generateGuid(),sourceTransaction);
Message<TPSEvent> message = new Message<TPSEvent>(event);
message.getHeader().setMessageType(TPSEvent.class.getName());
message.getHeader().setPayloadEncodingType(SystemCodecs.XML.name());
System.out.println(message.toString());
System.out.println(externalChannel.toString());
messageService.publish(externalChannel, message);
}
}
More Info
public Channel getEventsChannel() {
return Channel.builder()
.setName("necessarySources")
.setConnectionName("defaultConnection")
.setType(ChannelType.Topic)
.setConnectionData(AqSqlConnectionData.buildString(this.owner, "Safi"))
.setSubscriberNames(new String[]{"Safi_Autowire"})
.build();
}
Main Class
public class TPSHandler {
public static void main(String[] args) {
BatchExport batchExportBean=getBatchExportASJAXBElement();
System.out.println(" batchExportBean Trans Description : " + batchExportBean.getDueDate());
for(Pay pay :batchExportBean.getPay()) {
SourceTransaction sourceTransaction=mapPayBatchToSourceTransaction(pay,batchExportBean);
String sourceTraString = getSourceTransactionASXML(sourceTransaction);
System.out.println(" sourceTraString : \n" + sourceTraString);
MessagePublish messagePublish= new MessagePublish();
//SourceTransaction sourceTransaction= new SourceTransaction();
messagePublish.publishTPSMessage(sourceTransaction);
}
}
}
My 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:jaxrs="http://cxf.apache.org/jaxrs"
xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
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://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd
http://cxf.apache.org/jaxrs
http://cxf.apache.org/schemas/jaxrs.xsd">
<import resource="classpath:config-properties.xml" />
<import resource="classpath:datasource.xml" />
<import resource="classpath:transaction-manager.xml" />
<import resource="classpath:jmx.xml" />
<context:component-scan base-package="com.imosAdapter" />
<bean class="com.oasis.services.messaging.config.MessagingServicesConfig" />
<bean class="com.oasis.services.messaging.config.DefaultMessagingConnectorsConfig" />
<bean class="com.oasis.services.messaging.config.LoaderConfig" />
<context:annotation-config />
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>/config/oasis-component.properties</value>
</property>
</bean>
</beans>
The exception thrown:
Exception in thread "main" java.lang.NullPointerException
at com.imosAdapter.tps.events.MessagePublish.publishTPSMessage(MessagePublish.java:46)
at com.imosAdapter.tps.TPSHandler.main(TPSHandler.java:64)
What is the issue over here? Can anybody help me with this? what exactly I am missing here?
You need to initialize a Spring context at the start of your application when you do not create a servlet / run as a Server.
See Using Spring in a standalone application
I'm new to neo4j and spring in combination and spring at all. When I start debugging, I get the following exception:
Exception in thread "main"
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
bean named 'getSessionFactory' available
Can anyone help me please?
apllication-context.xml:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:neo4j="http://www.springframework.org/schema/data/neo4j"
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/data/neo4j
http://www.springframework.org/schema/data/neo4j/spring-neo4j.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="de.unileipzig.analyzewikipedia.neo4j" />
<!--neo4j:config storeDirectory="C:/temp/neo4jdatabase" base-package="de.unileipzig.analyzewikipedia.neo4j.dataobjects"/-->
<neo4j:repositories base-package="de.unileipzig.analyzewikipedia.neo4j.repositories"/>
<tx:annotation-driven />
<bean id="graphDatabaseService" class="org.springframework.data.neo4j.support.GraphDatabaseServiceFactoryBean"
destroy-method="shutdown" scope="singleton">
<constructor-arg value="C:/develop/uni/analyze-wikipedia-netbeans/database"/>
<constructor-arg>
<map>
<entry key="allow_store_upgrade" value="true"/>
</map>
</constructor-arg>
</bean>
</beans>
Startup-Class
package de.unileipzig.analyzewikipedia.neo4j.console;
import de.unileipzig.analyzewikipedia.neo4j.dataobjects.Article;
import de.unileipzig.analyzewikipedia.neo4j.service.ArticleService;
import java.io.File;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Neo4JConsole {
/**
* MAIN: start the java file
*
* #param args as string array
*/
public static void main(String[] args) {
String cwd = (new File(".")).getAbsolutePath();
ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
ArticleService service = (ArticleService) context.getBean("articleService");
Article art = createArticle();
createArticle(service, art);
System.out.println("Article created");
}
private static Article createArticle() {
Article article = new Article();
article.setTitle("Title");
return article;
}
private static Article createArticle(ArticleService service, Article art) {
return service.create(art);
}
}
Thank you.
Do you have this configuration?
#Configuration
#EnableNeo4jRepositories("org.neo4j.cineasts.repository")
#EnableTransactionManagement
#ComponentScan("org.neo4j.cineasts")
public class PersistenceContext extends Neo4jConfiguration {
#Override
public SessionFactory getSessionFactory() {
return new SessionFactory("org.neo4j.cineasts.domain");
}
}
For more information, try to look here
I am using spring 4.0.3.RELEASE
Here is my applicationContext.xml where i am configuring PropertyPlaceHolder
<?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:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="org.graphsearch.tutor.service.impls, org.graphsearch.tutor.dao.impls, org.graphsearch.tutor.configs, org.graphsearch.tutor.utils"/>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/properties/database/jdbc.properties</value>
<value>/WEB-INF/properties/alert/message.properties</value>
<value>/WEB-INF/properties/email/mail.properties</value>
<value>/WEB-INF/properties/logger/logging.properties</value>
</list>
</property>
</bean>
</beans>
In Email client class i am injecting property values like this
#Component
public class EmailClient {
#Value("${tutor.mail.common.note}")
private static String NOTE;
#Value("${tutor.mail.common.regards}")
private static String REGARDS;
#Value("${tutor.mail.from}")
private static String FROM;
#Autowired
private MailSender mailSender;
#Autowired
private Environment env;
public void sendRegisterMail(User user){
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(user.getEmailID());
String subject = env.getProperty("tutor.register.success.mail.subject"); //retuns null
String contentTemplate = env.getProperty("tutor.register.success.mail.content"); //returns null
MessageFormat format = new MessageFormat(contentTemplate);
Object[] args = {user.getFullName()};
StringBuffer content = new StringBuffer();
content.append(format.format(args));
content.append(NOTE);
content.append(REGARDS);
message.setSubject(subject);
message.setText(content.toString());
mailSender.send(message);
}
}
Now problem is #Value("${property.key}") does work like charm when i inject a private field of the class like NOTE, REGARDS, FROM.
But if i need this value inside the method sendRegisterMail()
#Value("$key") is giving compiler error. I searched on web few examples are there getting properties value through environment so i used like i have done in EmailClient class but it always give me null. I checked the log it says it can not find the property key.
Can some body give me a clue how to inject properties value inside a method.
Thanks in advance
Try
#Value("#{propertyConfigurer['tutor.mail.common.note']}")
private static String NOTE;
For more info have a look at How can I inject a property value into a Spring Bean which was configured using annotations?
My process class:
#Configurable("checkLicense")
public class CheckLicense {
String licensePath ;
#Value("${licenseKeyNotFound}")
String licenseKeyNotFound;
public boolean checkIn(String licensepath) {
System.out.println("hello "+licenseKeyNotFound);
licensePath = licensepath;
return checkIn();
}
}
My ApplicationContext.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"
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">
<bean class="com.smart.applicationlicense.CheckLicense"
scope="prototype">
</bean>
</beans>
Here is my properties file.
licenseKeyNotFound = License File Corrupted
Here is my servlet xml.
<context:property-placeholder location="conf/LicenseSettings.properties"
order="2" ignore-unresolvable="true" />
Eventhough I have used the #Configurable annotation along with the attributes Autowire.BY_NAME, Autowire.BY_TYPE, I am unable to initiate the variable of licenseKeyNotFound from the property file.
I was able to initiate the variable from a controller but not from this class which is declared #Configurable.
Can anyone please let me know what I am missing or what's wrong with my code?
Please let me know if there is something required from my code.
try this:
in your spring xml:
<context:property-placeholder location="classpath:your.properties" />
<context:load-time-weaver />
Try this
#Configurable
public class CheckLicense {
String licensePath;
String licenseKeyNotFound;
#Value("${licenseKeyNotFound}")
public void setLicenseKeyNotFound(String licenseKeyNotFound) {
this.licenseKeyNotFound = licenseKeyNotFound;
}
public boolean checkIn(String licensepath) {
System.out.println("hello " + licenseKeyNotFound);
licensePath = licensepath;
return checkIn();
}
}
in your properties file
licenseKeyNotFound=${value}
I have a message factory bean configured as shown below:
<?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:ws="http://www.springframework.org/schema/web-services"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/web-services
http://www.springframework.org/schema/web-services/web-services-2.0.xsd
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-3.0.xsd">
<bean id="soapMessageFactory" class="javax.xml.soap.MessageFactory" factory-method="newInstance" />
<bean id="saajMessageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory">
<constructor-arg ref="soapMessageFactory" />
</bean>
<bean id="myService" class="com.mypackage.TestEndPoint">
<property name="saajMessageFactory" ref="saajMessageFactory" />
</bean>
</beans>
The TestEndpoint class looks like this
#Endpoint
public class TestEndPoint {
ObjectFactory objectFactory = new ObjectFactory();
SaajSoapMessageFactory saajMessageFactory;
#PayloadRoot(namespace="http://ws.mypackage.com", localPart="downloadSaajMessageRequest")
#ResponsePayload
public JAXBElement<DownloadResponseSaajType> invoke(#RequestPayload DownloadSaajMessageRequest req, MessageContext context ) throws Exception {
DownloadResponseSaajType response = new DownloadResponseSaajType();
//DownloadResponseSaajType.PayLoad payload = new DownloadResponseSaajType.PayLoad();
DataHandler handler = new javax.activation.DataHandler(new FileDataSource("c:\\temp\\maven-feather.png"));
SaajSoapMessage message = saajMessageFactory.createWebServiceMessage();
message.addAttachment("picture", handler);
message.addAttachment("picture", handler);
//payload.setMessagePayLoad(handler);
//response.setPayLoad(payload);
response.setRequestName("NAMEOF");
context.setResponse(message);
return objectFactory.createDownloadSaajMessageResponse(response);
}
public void setSaajMessageFactory(SaajSoapMessageFactory saajMessageFactory){
this.saajMessageFactory = saajMessageFactory;
}
public SaajSoapMessageFactory getSaajMessageFactory(){
return saajMessageFactory;
}
}
I am having a few problems trying to get the endpoint to work and when i tried to debug the code i found that saajMessageFactory is never initialised and it is always null. Have i done something wrong with the configuration?
You have to add PayloadRootAnnotationMethodEndpointMapping bean to your configuration xml.
<bean class="org.springframework.ws.server.endpoint.mapping.PayloadRootAnnotationMethodEndpointMapping"/>