【问题标题】:How to connect to jdbc using @Bean in Spring MVC?如何在 Spring MVC 中使用 @Bean 连接到 jdbc?
【发布时间】:2016-04-24 21:44:39
【问题描述】:

我正在使用 Spring MVC。我正在尝试使用 DriverManagerDataSource 连接到 jdbc。我在用 @Bean 注解。我基本上是在尝试使用注释在 xml 文件中实现类似的功能。

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/jcg" />
    <property name="username" value="root" />
    <property name="password" value="toor" />
</bean>

我在我的配置类中使用@configuration 注解,这样做是为了在我的配置文件中使用@Bean 进行连接。

@Bean
public DriverManagerDataSource dataSource(){
    Properties jdbcProperties = PropertyUtils.getProperties(profile, "jdbc");
    
    DriverManagerDataSource ret = new DriverManagerDataSource();
    ret.setDriverClassName(jdbcProperties.getProperty("driverClassName"));
    ret.setUsername(jdbcProperties.getProperty("username"));
    ret.setPassword(jdbcProperties.getProperty("password"));
    ret.setUrl(jdbcProperties.getProperty("url"));
    return ret;
}

我在另一个 stackoverflow 问题中看到了这一点。这是正确的方法吗? 但我得到了错误。

属性无法解析

无法解析PropertyUtils

我不确定如何导入这些?另外我不明白这里的配置文件代表什么?你能帮忙吗?

【问题讨论】:

标签: java spring-mvc jdbc annotations spring-jdbc


【解决方案1】:

没有足够的信息来说明profile 变量和错误消息看起来像您没有导入PropertyUtils 类。

将属性导入 Spring 应用程序的正确方法之一是使用PropertySourcesPlaceholderConfigurer,正如我在评论中提到的那样。像这样在你的配置类中声明一个 bean。

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}

然后在你的配置类中指定属性文件名,并将配置文件放在类路径中。

@Configuration
@PropertySources({@PropertySource("classpath:database.properties")})
public class YourConfig {...}

为了使用属性文件中指定的属性,你需要注入一个Environment实例。

@Resource
private Environment environment;

然后用它来获取属性值。

@Bean
public DriverManagerDataSource dataSource(){
   DriverManagerDataSource ret = new DriverManagerDataSource();
   ret.setDriverClassName(environment.getRequiredProperty("driverClassName"));
   ret.setUsername(environment.getRequiredProperty("username"));
   ret.setPassword(environment.getRequiredProperty("password"));
   ret.setUrl(environment.getRequiredProperty("url"));
   return ret;
}

【讨论】:

  • 谢谢bunti,我能够解决这个问题。感谢您的帮助。
【解决方案2】:

我可以用这个来解决这个问题

@Bean
public DriverManagerDataSource dataSource(){
    DriverManagerDataSource ret = new DriverManagerDataSource();
    ret.setDriverClassName("driverClassName");
    ret.setUsername("username");
    ret.setPassword("password");
    ret.setUrl("url");
    return ret;
}

【讨论】:

    猜你喜欢
    • 2014-03-30
    • 2021-02-26
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 2012-06-01
    • 2019-03-15
    • 1970-01-01
    • 2021-05-16
    相关资源
    最近更新 更多