8 ways to declare Spring beans

Beginning Spring programming is simple, but it’s difficult to take over someone’s source code. In my opinion, it stems from different ways to declare Spring beans. I summarized 8 ways to declare Spring beans.

1. Xml based bean configuration

The bean itself is just a pojo class. Inside bean configuration xml, the following tag declare the class as a spring bean.

<bean id="firstBean" class="test.bean.FirstBean" />

2. Java based bean configuration

Bean configuration itself is a java class. By using @Bean annotation, an object is registered as a spring bean. AnnotationConfigApplicationContext loads Java based bean config.

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
import test.bean.PojoBean;

@Configuration
public class AppConfig {

	@Bean(name="pojoBean")
	public PojoBean getPojoBean() {
		return new PojoBean();
	}

}

3. @Component annotation (org.springframework.stereotype.Component)

Is the parent of @Service, @Repository and @Controller. And it is also equivalent to <bean> declaration.

4. @Service annotation (org.springframework.stereotype.Service)

Is a specific type of @Component. It usually means business logic. But the function is equivalent to @Component. (There is no difference between @Service and @Component inside Spring framework)

5. @Repository annoation (org.springframework.stereotype.Repository)

Is a specific type of @Component. It usually means DAO. If database exception is occured at @Repository bean, Spring translates it into DataAccessException.

6. @Controller annotation (org.springframework.stereotype.Controller)

Is a specific type of @Component. It means web controller. Usually @RequestMapping comes together. There are some children. (ex. @RestController)

7. @ManagedBean (javax.annotation.ManagedBean, JSR-250)

Is equivalent to @Component and @Service. No difference inside Spring.

8. @Named (javax.inject.Named, JSR-330)

Is equivalent to @Component and @Service. No difference inside Spring.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.