Spring @Componentアノテーションの使用

使用説明書

このアノテーションは、現在のクラスがコンポーネントクラスであることを宣言するために使用されます。Springは、クラスパススキャンによってこれらのコンポーネント自動的に検出して自動的にアセンブルします。各Beanを作成した後、Springコンテナに登録されます。

@Componentアノテーションが付けられたクラスと自動的に作成されたBeanの間には、暗黙的な1対1のマッピングがあります宣言する必要がある注釈は1つだけなので、他のプロセスは自動化されるため、Bean作成プロセスの制御の度合いは低くなります。

この注釈は次と同等です。

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

一般的なコンポーネント

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

名前付きコンポーネント

@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");

おすすめ

転載: www.cnblogs.com/danhuang/p/12690359.html