Sobes.tech
Junior — Middle

How can properties from application.properties be injected into a bean in Spring?

sobes.tech AI

Answer from AI

In Spring, properties from the application.properties file can be injected into beans in several ways:

  1. @Value annotation — allows injecting individual values by key:
@Component
public class MyBean {
    @Value("${my.property}")
    private String myProperty;

    // getters, methods
}
  1. Using @ConfigurationProperties — allows binding a group of properties to a class, convenient for structured settings:
@Component
@ConfigurationProperties(prefix = "my")
public class MyProperties {
    private String property;
    // getters and setters
}

And in application.properties:

my.property=value
  1. Via Environment — properties can be obtained programmatically:
@Autowired
private Environment env;

public void someMethod() {
    String value = env.getProperty("my.property");
}

Most often, @Value is used for simple cases, and @ConfigurationProperties for groups of related settings.