WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Spring Boot & Hibernate · Advanced · question 46 of 100

How do you use Spring Boot’s @Value annotation to inject configuration properties into beans?

📕 Buy this interview preparation book: 100 Spring Boot & Hibernate questions & answers — PDF + EPUB for $5

Spring Boot’s @Value annotation is a powerful tool for injecting configuration properties into beans. The @Value annotation can be used to inject property values from a variety of sources, including configuration files, environment variables, and command-line arguments.

Here’s an example of how to use the @Value annotation to inject a property value into a bean:

    @Component
    public class MyBean {
        @Value("${my.property}")
        private String myProperty;
        
        public void doSomething() {
            System.out.println("My property value is: " + myProperty);
        }
    }

In this example, we’ve annotated our MyBean class with @Component to ensure that it’s picked up by Spring’s component scanning. We’ve also annotated the myProperty field with @Value("$my.property") to inject the value of the my.property property from our configuration files. The value of this property will be stored in the myProperty field, which we can then use in our doSomething() method.

Note that the $my.property syntax is used to specify the property value. The actual value of the property will be determined by the Spring Environment, which can resolve property values from a variety of sources.

You can also use the @Value annotation to inject values from other sources, such as environment variables or command-line arguments. For example, you might use the following syntax to inject an environment variable into a bean:

    @Component
    public class MyBean {
        @Value("\${MY\_ENV\_VAR}")
        private String myEnvVar;
        
        public void doSomething() {
            System.out.println("My environment variable value is: " + myEnvVar);
        }
    }

In this example, we’re injecting the value of the MY_ENV_VAR environment variable into our MyBean class using the @Value annotation.

Overall, the @Value annotation is a powerful tool for injecting configuration properties into beans in a Spring Boot application. It can be used to inject values from a variety of sources, and can greatly simplify the process of configuring your application.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Spring Boot & Hibernate interview — then scores it.
📞 Practice Spring Boot & Hibernate — free 15 min
📕 Buy this interview preparation book: 100 Spring Boot & Hibernate questions & answers — PDF + EPUB for $5

All 100 Spring Boot & Hibernate questions · All topics