Java 如何在Spring Boot中将applications.properties添加到组件中?

Java 如何在Spring Boot中将applications.properties添加到组件中?,java,mysql,spring,spring-boot,vaadin,Java,Mysql,Spring,Spring Boot,Vaadin,我使用的是Vaadin14,我想将它们包含到SpringBoot的组件类中 # Database spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto=update spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect spring.datasource.url=jdbc:mysql://localhost:3306/test?createDa

我使用的是Vaadin14,我想将它们包含到SpringBoot的组件类中

# Database
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
spring.datasource.url=jdbc:mysql://localhost:3306/test?createDatabaseIfNotExist=true&serverTimezone=CET
spring.datasource.username=myUser
spring.datasource.password=myPassword
我想让它看起来像这样。在这里,我可以在
视图中包含带有
@Autowired
的类
FTPConnection
,然后在需要时对其进行更改

但是它们是通过
@PropertySource(“classpath:ftp.properties”)
导入的,而
应用程序则不是。那么,我如何动态地更改例如
spring.security.user.name=myUser
?我需要创建一个
组件
类还是什么

@Component
@PropertySource("classpath:ftp.properties")
public class FTPConnection {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${ftp.connectionPath}")
    private String connectionPath; // e.g ftp.example.org/folder/path
    
    @Value("${ftp.password}")
    private String password;
    
    @Value("${ftp.username}")
    private String username;

您不必显式引用
application.properties
,因为springboot无论如何都会选择它(当然,除非您谈论的是一个具有该名称但位于其他地方的文件)
@Value(…)
应使用
application.properties
(或任何其他来源,如envvars或via profiles)中的值。@cfrick在数据库删除时,我始终使用
application.properties
。现在我想创建一个组件类,在其中创建数据库连接。有办法吗?我不知道你在问什么。从示例中删除
@PropertySource
,将
@Value
更改为要注入的值(或者更好,检查spring是否有一些DatasourceConfiguration或DatasourceProperties类)。然后,您可以在@PostConstruct中创建连接或任何合适的连接。除此之外,如果你能展示你的实际问题、失败的代码和你所得到的错误,这会有所帮助?