Plan 1:
Using PropertiesLoaderUtils
import ;
import ;
import ;
import ;
public static Properties readPropertiesFile(String fileName) {
try {
Resource resource = new ClassPathResource(fileName);
Properties props = (resource);
return props;
} catch (Exception e) {
("Read configuration file:" + fileName + "Exception, read failed");
();
}
return null;
}
Properties properties = readPropertiesFile("");
((""));
Plan 2:
Using Environment
import ;
@Autowired
private Environment environment;
((""));
Plan 3:
Use @Value
import ;
@Value("${}")
private String rabbitmqHost;
(rabbitmqHost);
Plan 4:
Using @ConfigurationProperties
Attribute Class
import ;
import ;
import ;
@Getter
@Setter
@ConfigurationProperties(prefix = "")
public class TestProperties {
private String host;
private String port;
private String username;
private String password;
}
Register attribute configuration class
import ;
import ;
@EnableConfigurationProperties()
@SpringBootConfiguration
public class TestConfiguration {
}
Use configuration classes
@Autowired
private TestProperties testProperties;
(());
static static method read configuration
@Component
public class UserUtil {
// Use @Value annotation to read the configuration
@Value("${}")
private String name;
// Set static member variables to receive the value injected by @Value
private static String userName;
// Use @PostConstruct annotation for static variable assignment
@PostConstruct
public void getUserName() {
userName = ;
}
// Test whether the static variable is assigned to the test method
public static String test() {
return userName;
}
}
Call example:
String name = ();
Using the @Component property annotation indicates that it needs to be loaded when the startup class Application is started.