首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >来自Spring3的@Value注释在我的程序中不起作用

来自Spring3的@Value注释在我的程序中不起作用
EN

Stack Overflow用户
提问于 2011-11-23 16:03:41
回答 2查看 1.3K关注 0票数 1

我正在用Spring3编写一个java应用程序,它可以很好地处理xml,但在注释方面完全不起作用。

下面是我的代码片段:

代码语言:javascript
运行
复制
@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;
     }
 }

我的ApplicationContext.xml是这样的:

代码语言:javascript
运行
复制
<?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是这样的:

代码语言:javascript
运行
复制
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());
   }
}

你猜怎么着?结果为空。有什么问题吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-11-23 18:02:50

这里的问题是使用xmlbeanfactory,这是一个常见的错误。试着这样做,它将完美地工作:

代码语言:javascript
运行
复制
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
OracleDatabase oracleDB = (OracleDatabase)context.getBean("oracleDB");
...

我认为beanfactory不足以处理@Value注释。更多信息可以在here上找到。

票数 1
EN

Stack Overflow用户

发布于 2011-11-23 17:08:21

如果你已经在使用Spring了,为什么要通过这种方式连接,而不是使用Spring的DataSources呢?往好里说看起来很奇怪;往坏里说就是错误的。

我会给那个仓库一个JdbcTemplate。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8238878

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档