I have this code...
public static void main(String[] args)
{
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
}
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"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
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">
</beans>
The code exits, but the JVM never stops.
Anyone any ideas why its doesn't stop?
I've also tried a new Main method of the following, but it keeps running.
public static void main(String[] args)
{
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
((ConfigurableApplicationContext)context).registerShutdownHook();
((ConfigurableApplicationContext)context).stop();
System.out.println("exiting NOW...");
}
If I pause the JVM, it shows 4 threads.
1 with TimerThread.run()
3 with ScheduledThreadPoolExecutor.take()
The ConfigurableApplicationContext interface (that ClassPathXmlApplicationContext implements) has a close method you need to call in order for the JVM to shut down properly.
More information can be found here.
Related
Hi I would like to read values from application.properties. I have found that this should work:
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("application-context.xml");
Environment environment = applicationContext.getEnvironment();
System.out.println("STARTING:");
System.out.println("Connecting to: "+environment.getProperty("datasource"));
}
but I am getting null for datasource value.
my application-context.xml looks like this:
<?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.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:application.properties" />
</beans>
could someone tell me where could be problem?
Please follow this blog.
https://zetcode.com/spring/propertyplaceholder/
This will explain to you how you can to use the application.properties values.
Please Map your been with "application.properties" values
<bean id="dataSource" class="org.springframework.jdbc.datasource.
SimpleDriverDataSource">
<property name="url" value="${db.url}"></property>
<property name="username" value="${db.username}"></property>
<property name="password" value="${db.password}"></property>
</bean>
and Use
public static void main(String[] args) {
var ctx = new GenericXmlApplicationContext("my-beans.xml");
var dataSource = (SimpleDriverDataSource) ctx.getBean("dataSource");
logger.info("Url: {}", dataSource.getUrl());
logger.info("User name: {}", dataSource.getUsername());
logger.info("Password: {}", dataSource.getPassword());
ctx.close();
}
I am trying to run Task scheduler but I get below error:
"C:\Program Files\Java\jdk1.8.0_121\bin\java" com.mthree.util.App
Error: Could not find or load main class com.mthree.util.App
Process finished with exit code 1
FixedRateScheduler code
import org.springframework.scheduling.annotation.Scheduled;
import java.util.Date;
public class FixedRateScheduler {
#Scheduled(fixedRate = 1000)
public void run() throws InterruptedException{
System.out.println("livePrice: "+ new Date());
Thread.sleep(3000);
}
}
LivePrice-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:task="http://www.springframework.org/schema/cache"
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-3.1.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
<task:annotation-driven />
<mvc:annotation-driven />
<context:annotation-config />
<bean id="fixedRateScheduler" class="com.mthree.util.FixedRateScheduler" ></bean>
<context:component-scan base-package="com.mthree.*" />
Main Class - App.java
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String [] args){
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("LivePrice-servlet.xml");
}
}
directory structure
This question has already an answer here but i've checked and the component:scan is set roperly for me so i don't really get what is the point here. The controller:
#Controller
#RequestMapping("view")
public class PortletController {
#RenderMapping
public String view(RenderRequest request, RenderResponse response, ModelMap model) {
ResourceURL baseResourceUrl = response.createResourceURL();
model.addAttribute("ajaxURL", baseResourceUrl.toString() + "&");
model.addAttribute("standalone", false);
model.addAttribute("portletId", getPortletId(request));
model.addAttribute("portletAppContextPath", request.getContextPath() + "/");
return "index";
}
The component scan element in the applicationcontext is:
<?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.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- DispatcherPortlet Context: defines this portlet's request-processing infrastructure -->
<!-- Autodetect annotated controllers -->
<context:component-scan base-package="com.package.of.controller"/>
</beans>
Any idea of why it could be not working?
I want to record execution time of my service method.
I think AOP is a easy way to do, so I wrote an Aspect:
#Aspect
public class ServiceLogAdviceAspect {
private static Logger LOG = LoggerFactory.getLogger(ServiceLogAdviceAspect.class);
#Around("execution(* com.j1.**.service.*(..))")
public Object doBasicProfilingTime(ProceedingJoinPoint joinPoint) throws Throwable {
String methodName = joinPoint.getSignature().getName();
Object target = joinPoint.getTarget();
long start = System.currentTimeMillis();
Object retVal = joinPoint.proceed();
long end = System.currentTimeMillis();
LOG.error(String.format("Invoke [%s$%s] Takes %d ms", target.getClass().getCanonicalName(), methodName, (end - start)));
return retVal;
}
}
and Spring config:
<?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-3.0.xsd"
default-autowire="byName">
<aop:aspectj-autoproxy/>
<bean id="logAdviceAspect"
class="com.j1.soa.common.aspect.ServiceLogAdviceAspect"></bean>
</beans>
But when I invoke the method
public ServiceMessage<GoodsDetailDto> getGoodDetail(GoodsDetailDto goodsDetailDto)
I get neither error output nor into the breakpoint.
EDIT
getGoodDetail is defined in class
com.j1.soa.resource.item.service.GoodsDetailServiceImpl
And I am calling it using Hessian RPC,
First defined spring bean of Remote Service in application-context-rpc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="goodsDetailService" class="org.springframework.remoting.caucho.HessianProxyFactoryBean">
<property name="serviceUrl" value="http://api.soa.item.j1.com/hessian/goodsDetailService" />
<property name="serviceInterface" value="com.j1.soa.resource.item.api.GoodsDetailService" />
<property name="readTimeout" value="6000"/>
</bean>
</beans>
Then defined it in client
#Autowired
private GoodsDetailService goodsDetailService;
And using it
GoodsDetailDto goodsDetailDto = new GoodsDetailDto();
goodsDetailDto.setGoodsId(NumericUtil.parseLong(goodsId));
goodsDetailDto.setProductId(NumericUtil.parseInt(productId));
goodsDetailDto.setSiteType(SiteType.MOBILE);
ServiceMessage<GoodsDetailDto> detailResult = goodsDetailService
.getGoodDetail(goodsDetailDto);
You should include logAdviceAspect in <aop:aspectj-autoproxy/>
<aop:aspectj-autoproxy>
<aop:include name="logAdviceAspect"/>
</aop:aspectj-autoproxy>
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.