在Spring Boot项目中,application.properties文件内容如下:
#mongo配置
spring.data.mongodb.host =
spring.data.mongodb.port = 27017
#spring.data.mongodb.username=user1
#spring.data.mongodb.password=
spring.data.mongodb.database=
spring.main.allow-bean-definition-overriding=true
data.mongodb.prefix=pics
我们如果需要在外部文件使用上面的属性,可以使用@PropertySource注解和@Value注解实现,该方法也适合其他配置文件
@Service
@PropertySource("classpath:application.properties")
public class MongoServiceImp implements MongoService {
@Autowired
protected GridFsOperations operations;
@Value("${spring.data.mongodb.host}")
private String host1;
@Value("${data.mongodb.prefix}")
private String prefix1;
@Override
public String getFileUrl(String fileName) {
//从配置文件中获取
StringBuilder host = new StringBuilder(host1);
StringBuilder prefix = new StringBuilder(prefix1);
//拼接成新的url
StringBuilder result = new StringBuilder();
result.append("http://" + host);
result.append("/");
result.append(prefix);
result.append("/");
result.append(fileName);
return result.toString();
}