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

Spring Framework · Advanced · question 42 of 100

How can you configure a Spring Bean using Java-based configuration instead of XML-based configuration?

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

Spring provides two ways of defining and configuring beans, XML-based and Java-based configuration. While XML configuration is widely used, Java-based configuration has gained popularity among Spring developers due to its simplicity, type-safety, and code readability. Here are the steps to configure Spring Beans using Java-based configuration:

1. Enable Java-based configuration: To use Java-based configuration in a Spring application, you need to enable it by adding the ‘@Configuration‘ annotation to a Java class. This annotation indicates that the class contains Spring configuration information.

@Configuration
public class AppConfig {
    // bean definitions go here
}

2. Define the Beans: To define a Bean in Java-based configuration, you can create a method and annotate it with ‘@Bean‘. The method should return the bean that you want to configure.

@Configuration
public class AppConfig {

    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

3. Customizing Bean Properties: If you need to set custom properties of a bean, you can do so by calling bean methods on the created bean instance.

@Configuration
public class AppConfig {

    @Bean
    public MyBean myBean() {
        MyBean bean = new MyBean();
        bean.setFoo("foo");
        bean.setBar("bar");
        return bean;
    }
}

4. Injecting dependencies: You can inject dependencies into a bean by specifying method parameters annotated with ‘@Autowired‘.

@Configuration
public class AppConfig {

    @Bean
    public MyBean myBean(Foo foo, Bar bar) {
        return new MyBean(foo, bar);
    }
}

5. Importing Configuration classes: If your application has multiple configuration classes, you can import them into a main configuration class using the ‘@Import‘ annotation.

@Configuration
@Import({DataSourceConfig.class, MailConfig.class})
public class AppConfig {
    // bean definitions go here
}

In conclusion, Spring Framework provides a flexible and powerful configuration mechanism for creating and managing beans, and the Java-based configuration approach provides a better way to write the configuration in a type-safe and easy-to-understand manner.

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

All 100 Spring Framework questions · All topics