gpt4 book ai didi

java - 如何在 Java Spring 4.0.4 中使用 @PropertySource?

转载 作者:行者123 更新时间:2023-12-02 10:52:15 24 4
gpt4 key购买 nike

我想将 ProjectName/src/database.properties 中的 database.properties 源添加到 AppConfig.class 中,其中位于 ProjectName/src/device/spring/config 中,根据https://www.journaldev.com/17053/spring-jdbctemplate-example

import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import tekranchecklist.model.*;



@Configuration
@ComponentScan("device.spring.dao","device.model","device.spring.config","device.Main")

public class AppConfig {
@Autowired
Environment environment;

private final String URL = "URL";
private final String USER = "root";
private final String DRIVER = "DRIVER";
private final String PASSWORD = "PASSWORD";

@Bean
DataSource dataSource() {
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setUrl(environment.getProperty(URL));
driverManagerDataSource.setUsername(environment.getProperty(USER));
driverManagerDataSource.setPassword(environment.getProperty(PASSWORD));
driverManagerDataSource.setDriverClassName(environment.getProperty(DRIVER));
return driverManagerDataSource;
}

}

我尝试使用@PropertySource("classpath:database.properties"),但语法错误:需要类、接口(interface)或枚举。有人可以帮助我如何使用 @PropertySource 添加我的 .properties 文件路径吗?

最佳答案

@PropertySource 是一个注解,只能用于类型,即接口(interface)、类、枚举:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(PropertySources.class)
public @interface PropertySource {...}

预期的类、接口(interface)或枚举消息是一个编译错误,这意味着您在与类型不匹配的目标上指定了注释。

所以将其移动到正确的位置:

@PropertySource("classpath:database.properties")
public class AppConfig {
....
}

关于java - 如何在 Java Spring 4.0.4 中使用 @PropertySource?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52073198/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com