I’m writing a java application with Spring 3.It’s working well with xml,but not working at all in annotation.
here’s my snippet:
@Service("oracleDB")
public class OracleDatabase implements IDatabase
{
@Value("oracle.jdbc.driver.OracleDriver")
private String driverName;
@Value("jdbc:oracle:thin:@")
private String url;
public String getDriverName()
{
return driverName;
}
}
My ApplicationContext.xml is 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-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<context:component-scan
base-package="com.pdiwt.database"></context:component-scan>
</beans>
MyInvoker is like that:
public class MyInvoker{
public static void main(String args[]){
XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
OracleDatabase oracelDB = beanFactory.getBean("oracleDB");
System.out.println(oracleDB.getDriverName());
}
}
guess what? The result is null. Is there anything wrong?
The problem here is using xmlbeanfactory, which is a common mistake. Try this instead, it will work perfectly:
I think the beanfactory is simply not powerful enough to handle the @Value annotations. More information can be found here.