Use of Spring @Component annotation

Instructions for use

This annotation is used to declare that the current class is a component class. Spring will automatically detect and automatically assemble these components through class path scanning , create a bean, and register it with the Spring container.

There is an implicit one-to-one mapping between the class annotated with @Component and the automatically created bean . Since only one annotation needs to be declared, other processes are automated, so the degree of control over the bean creation process is low.

This annotation is equivalent to:

<bean id="useService" class="com.test.service.UserServiceImpl"/>

Common components

@Component
public class UserServiceImpl implements IUserService {
	private String name;
	// getter&&setter...
}
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
IUserService service = (IUserService)context.getBean(UserServiceImpl.class);

Named component

@Component(value = "userService")
public class UserServiceImpl implements IUserService {
	private String name;
	// getter&&setter...
}
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
IUserService service = (IUserService)context.getBean("userService");

Guess you like

Origin www.cnblogs.com/danhuang/p/12690359.html