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();
}
Related
Gratitude: Thanks for your support.
Problem Description:
I am facing an exception while trying to run the below code. Don't even have a clue.
How to write the xml definition to initiate Dependent class using #Autowired Constructor with int parameter.
ExceptionMessage:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'dependent' defined in class path
resource [simple-context.xml]:
Could not resolve matching constructor (hint: specify index/type/name arguments
for simple parameters to avoid type ambiguities)
filename: spring-context.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:c="http://www.springframework.org/schema/c"
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">
<context:component-scan base-package="com.learning.spring.constinjection" />
<bean id="dependency" class="com.learning.spring.constinjection.Dependency"></bean>
<bean id="dependent" class="com.learning.spring.constinjection.Dependent">
<constructor-arg ref="dependency" name="dpcy" />
<constructor-arg name="mesg" value="Hi this is a test mesg" />
</bean>
<bean id="dependent2" class="com.learning.spring.constinjection.Dependent"
c:mesg="Hi, this is another test mesg" />
</beans>
filename: Dependent.java
public class Dependent {
Dependency dpcy;
Dependent(Dependency dpcy, String mesg){
this.dpcy = dpcy;
System.out.println("Message is: " + mesg);
}
Dependent(String mesg){
System.out.println("Only Message is: " + mesg);
}
#Autowired
Dependent(Integer ticketno){
System.out.println("Ticket no is: " + ticketno);
}
}
filename: Dependency.java
public class Dependency {
Dependency(){
System.out.println("Dependency loaded successfully");
}
}
filename: ConstructorInjectionApp
public class ConstructorInjectionApp {
public static void main(String[] args) {
GenericXmlApplicationContext gen = new GenericXmlApplicationContext();
gen.load("classpath:simplespringconstinjection.xml");
gen.refresh();
Dependent d = (Dependent) gen.getBean("dependent");
Dependent d2 = (Dependent) gen.getBean("dependent2");
}
}
By changing this:
<bean id="dependent" class="com.learning.spring.constinjection.Dependent">
<constructor-arg ref="dependency" name="dpcy" />
<constructor-arg name="mesg" value="Hi this is a test mesg" />
</bean>
to this:
<bean id="dependent" class="com.learning.spring.constinjection.Dependent"
c:dpcy-ref="dependency" c:mesg="Hi, this is another test mesg" />
I was able to get the ApplicationContext to properly initialize with no errors.
See this Spring doc for information on the "c" namespace.
There is still an issue with the constructor with the #Autowired annotation.
I am trying to call mainframe stored procedure using TempStatusClass in this class I am loading status-dao.xml which has the datasource defined and stored procedure defined. When I try to call this I am getting following exception org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testProcedure' defined in class path resource [status-dao.xml]: Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities).
Not sure what is causing this. Any help is highly appreciated.
#TempStatusClass
public class TempStatusClass implements DataServiceIF{
#Override
public Object execute(Object param) throws AppException {
StatusUpdateVO input = new StatusUpdateVO();
input.setShipment("X3328332842");
Map dataMap = null;
String springConfig = "status-dao.xml";
ApplicationContext context =new ClassPathXmlApplicationContext(springConfig);
StatusUpdateImpl statusUpdate = (StatusUpdateImpl) context.getBean("statusUpdateDao");
try {
dataMap = statusUpdate.getData(input);
} catch (StatusUpdateDAOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dataMap;
}
}
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"
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.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<context:component-scan base-package="com.ops.test.test.*" />
<!-- Step 1: Define the data source -->
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="jdbc/MAINEFRAME" />
</bean>
<!-- Step 2: Define JDBC template -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- Step 3: Define Stored Procedures -->
<bean id="testProcedure"
class="com.ops.test.test.sp.StatusUpdateStoredProcedure">
<constructor-arg>
<ref bean="jdbcTemplate" />
</constructor-arg>
<constructor-arg value="D472J00.N472RPTL" />
</bean>
<!-- Step 4: Define the DAOs -->
<bean id="statusUpdateDao"
class="com.ops.test.test.dao.impl.StatusUpdateImpl">
<property name="dataSource" ref="dataSource" />
<property name="procedure" ref="testProcedure" />
</bean>
</beans>
Impl
public class StatusUpdateImpl extends JdbcDaoSupport implements StatusUpdateDao{
/** The data source. */
private DataSource dataSource;
/** The stored procedure. */
private StatusUpdateDao storedProcedure;
/** The jdbc template object. */
#Autowired
private JdbcTemplate jdbcTemplateObject;
public StatusUpdateImpl()
{
}
#Autowired
public StatusUpdateImpl(DataSource dataSource) {
setDataSource(dataSource);
JdbcTemplate jdbcTemplate = getJdbcTemplate();
}
public void setStoredProcedure(StatusUpdateDao storedProcedure)
{
this.storedProcedure = storedProcedure;
}
public Map getData(Object input) throws StatusUpdateDAOException {
Map data = storedProcedure.getData(input);
return data;
}
}
Are you using spring-data-commons RC1 version? I have the same problem and it started with version bump of this dependency. I created an issue on spring's jira as well:
https://jira.spring.io/browse/DATASOLR-348
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 created a DAO (ForecastPersistorDao.java) which is the interface and its corresponding implementation (ForecastPersistorDaoImpl.java). The implementation has a method 'persist()' whose job is to persist some data into the database. When I try to call persist to persist the data, it throws a NullPointerException since it does not initialize SessionFactory properly. Please help me point out what I might be doing wrong:
ForecastPersistorDao.java
public interface ForecastPersistorDao {
void persist(List<ForecastedDemand> forecastedDemands);
List<DemandForecast> retrieveLastForecast(String marketplaceId);
}
ForecastPersistorDaoImpl.java
#Repository("forecastPersistorDao")
public class ForecastPersistorDaoImpl implements ForecastPersistorDao {
private SessionFactory sessionFactory;
#Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
/**
* Persist forecast in the database for later
*
* #param forecastedDemands
* List of forecast for all asin:marketplaceId tuple
*/
#Transactional
#Override
public void persist(List<ForecastedDemand> forecastedDemands) {
System.out.println("THIS IS ALWAYS NULL-------->>>>>>>> " + sessionFactory);
Session session = sessionFactory.getCurrentSession();
Date forecastCalculationDate = new Date();
// For each [asin:marketplace] tuple
for (ForecastedDemand forecastedDemand : forecastedDemands) {
String asin = forecastedDemand.getAsinMarketplaceId().getAsin();
String marketplaceId = forecastedDemand.getAsinMarketplaceId().getMarketplaceId();
String forecastingModel = forecastedDemand.getForecastingModel();
SortedMap<Instant, Double> forecast = forecastedDemand.getForecast();
// for each forecast date - write an entry in demand_forecasts table
for (Map.Entry<Instant, Double> entry : forecast.entrySet()) {
Date dateOfForecast = entry.getKey().toDate();
double quantityForecasted = entry.getValue();
DemandForecast forecastToPersist = new DemandForecast(asin, marketplaceId, forecastCalculationDate,
forecastingModel, quantityForecasted, dateOfForecast);
session.save(forecastToPersist);
}
}
}
Main class (Runner.java):
public final class FbsRunner {
private ForecastPersistorDao forecastPersistorDao;
public static void main(String[] args) {
Runner runner = new Runner();
runner.run();
}
public void run() {
ApplicationContext context =
new FileSystemXmlApplicationContext("spring-configuration/application-config.xml");
forecastPersistorDao = (ForecastPersistorDao) context.getBean("forecastPersistorDao"); // this works fine
System.out.println(">>>>>>>>>> forecastPersistorDao [this is fine (not null)]: " + forecastPersistorDao);
List<ForecastedDemand> forecastedDemand = [a list of Forecasted demand to be persisted int he DB]
// THE CALL BELOW FAILS...
forecastPersistorDao.persist(forecastedDemands);
System.out.println("Persisted demand in the database"); // We don't reach here.
}
}
spring-configuration/application-config.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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
">
<!-- The main application context spring configuration -->
<import resource="application/hibernate.xml" />
<import resource="common/hibernate.xml" />
<!--<import resource="application/proxies.xml" />-->
<!--<import resource="common/aggregators.xml" /> -->
<import resource="application/environment.xml" />
<!--
Add any beans specific to your application here
-->
<bean id="forecastPersistorDao" class="com.amazon.fresh.fbs.dao.ForecastPersistorDaoImpl" />
</beans>
application/hibernate.xml:
<bean id="SessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
parent="AbstractSessionFactory" depends-on="EnvironmentHelper" >
<property name="hibernateProperties">
...
...
everything as expected
...
</bean>
common/hibernate.xml:
<beans ... >
bean id="AbstractSessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
abstract="true">
<property name="mappingResources">
<list>
<value>com/amazon/fresh/fbs/dao/hibernate/RtipData.hbm.xml</value>
<value>com/amazon/fresh/fbs/dao/hibernate/Vendor.hbm.xml</value>
<value>com/amazon/fresh/fbs/dao/hibernate/AdjustmentPeriod.hbm.xml</value>
<value>com/amazon/fresh/fbs/dao/hibernate/DemandForecast.hbm.xml</value>
</list>
</property>
<property name="exposeTransactionAwareSessionFactory">
<value>true</value>
</property>
</bean>
<!-- Use Spring transactions for Hibernate -->
<tx:annotation-driven transaction-manager="txManager" mode='proxy' proxy-target-class='true'/>
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="SessionFactory" />
</bean>
<aop:aspectj-autoproxy/>
</beans>
Please try to add <context:component-scan base-package="YOUR PACKAGE NAME" /> into your application-config.xml. This will tell Spring to scan for annotated components that will be auto-registered as Spring beans.
"YOUR PACKAGE NAME" should be the package name to scan for annotated components.
sessionFactory didn't autowired correctly ,add "#component" for ForecastPersistorDaoImpl and add "context:component-scan" in application-config.xml to tell spring to initialize.
I am using Spring 3.1 as standalone app.
I have some wierd situation and I guess I am missing something.
I have class which has method that I have exposed via JMX console.
that method is invoking a method via bean.
that bean I am initializing in advaned.
the wierd thing that after i am invoking the method via the jmx console the bean instance turn to be null.
Thats the JMX bean which is exposed:
public class TriggerBean implements IJmxTriggerBean
{
static Logger logger = Logger.getLogger(TriggerBean.class);
FeedListenerBean fe = null;
public void start()
{
try
{
// init();
PropertyConfigurator.configure(FixGWConstants.LOG4J_PATH);
ApplicationContext context = new ClassPathXmlApplicationContext(FixGWConstants.APPLICATION_CONTEXT_XML);
fe = (FeedListenerBean) context.getBean("FeedListenerBean");
doTheListen();
}
catch (Throwable t)
{
logger.error(t);
System.out.println(t);
}
}
//thats the method being exposed by jmx. pay attention that fe object has been initialized before by the start()
public void doTheListen()
{
fe.listen();
}
private void init()
{
Resource resource = new ClassPathResource(System.getProperty("user.dir") + "//config.properties");
try
{
Properties props = PropertiesLoaderUtils.loadProperties(resource);
String log4jPath = props.getProperty("LOG4J_PATH");
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I am testing it via standalone:
public static void main(String[] args) throws Exception
{
protected TriggerBean trigger = new Trigger();
trigger.start();
}
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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" 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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- Must for auto wiring
<context:annotation-config />
-->
<context:component-scan base-package="com.fixgw.beans">
</context:component-scan>
<!-- start a JMX Server -->
<bean id="mbeanServer" class="org.springframework.jmx.support.MBeanServerFactoryBean" />
<bean id="FeedListenerBean" class="com.fixgw.beans.FeedListenerBean">
</bean>
<bean id="TriggerBean" class="com.fixgw.test.TriggerBean">
</bean>
<bean id="exporter" class="org.springframework.jmx.export.MBeanExporter">
<property name="beans">
<map>
<entry key="Server:name=HttpAdaptor">
<bean class="mx4j.tools.adaptor.http.HttpAdaptor">
<property name="port" value="8000" />
<property name="host" value="0.0.0.0" />
<property name="processor">
<bean class="mx4j.tools.adaptor.http.XSLTProcessor" />
</property>
</bean>
</entry>
<entry key="bean:name=TriggerBean" value-ref="TriggerBean" />
</map>
</property>
<property name="listeners">
<list>
<!--
let the HttpAdapter be started after it is registered in the
MBeanServer
-->
<bean class="com.fixgw.jmx.HttpAdaptorMgr">
<property name="mbeanServer" ref="mbeanServer" />
</bean>
</list>
</property>
</bean>
</beans>
When I first using start() the object fe is doing great.
but after invoking doTheListen( via JMX the object fe remind null(although it has already been initialized before)
any idea?
thanks,
ray.