top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What are different ways to configure a class as spring bean?

0 votes
496 views
What are different ways to configure a class as spring bean?
posted Nov 12, 2017 by Frank Lee

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

There are three different ways to configure Spring Bean:-

1 XML Configuration: This is the most popular configuration and we can use bean element in context file to configure a Spring Bean.
For example:

<bean name="myBean" class="com.test.spring.beans.MyBean"></bean>

2 Java Based Configuration: If you are using only annotations, you can configure a Spring bean using @Bean annotation. This annotation is used with @Configuration classes to configure a spring bean. Sample configuration is:

@Configuration
@ComponentScan(value="com.test.spring.main")
public class MyConfiguration {
@Bean
public MyService getService(){
return new MyService();
}}

3 Annotation Based Configuration: We can also use @Component, @Service, @Repository and @Controller annotations with classes to configure them to be as spring bean. For these, we would need to provide base package location to scan for these classes.
For example:

<context:component-scan base-package="com.test.spring" />
answer Nov 15, 2017 by Jon Deck
...