在Spring Boot中,可以通过使用@Value注解或@ConfigurationProperties注解来读取外部文件内容。
@Value注解读取外部文件内容:import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;@Componentpublic class MyComponent { @Value("${my.property}") private String myProperty; // 使用myProperty}在上面的例子中,${my.property}表示从application.properties或application.yml配置文件中读取my.property属性的值。
@ConfigurationProperties注解读取外部文件内容:首先,在application.properties或application.yml配置文件中定义属性:
my.property=value然后创建一个配置类来绑定属性:
import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;@Component@ConfigurationProperties(prefix = "my")public class MyProperties { private String property; // Getter and Setter}在上面的例子中,@ConfigurationProperties(prefix = "my")表示将以my为前缀的属性绑定到MyProperties类中的属性上。
最后,在需要使用外部文件内容的地方注入MyProperties类即可:
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;@Componentpublic class MyComponent { @Autowired private MyProperties myProperties; // 使用myProperties.getProperty()}通过以上两种方式,Spring Boot可以方便地读取外部文件中的内容。


