Springでの注記@Beanと@Componentの違い

2317 ワード

1,@Componentはクラスで使用され、このクラスがspringによって管理されていることを宣言します.
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface Component {

	/**
	 * The value may indicate a suggestion for a logical component name,
	 * to be turned into a Spring bean in case of an autodetected component.
	 * @return the suggested component name, if any (or empty String otherwise)
	 */
	String value() default "";

}


2,@Beanはメソッドに作用し,一般に返されるオブジェクトがSpringによって直接管理されることを示す.
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Bean {

	/**
	 * Alias for {@link #name}.
	 * 

Intended to be used when no other attributes are needed, for example: * {@code @Bean("customBeanName")}. * @since 4.3.3 * @see #name */ @AliasFor("name") String[] value() default {};


同じ:クラスがSpringによって管理されることを宣言します.異なる点:作用targetが異なる
例1,@Component
..
@Component // Not a controller?! Makes no difference
@RequestMapping(″/component/message″)
public class ComponentController {
  ..
}
import org.springframework.stereotype.Service;
..
@Service // Not a controller?! Makes no difference
@RequestMapping(″/service/message″)
public class ServiceController {
  ..
}

例2,@Bean:
// Just a POJO
public class MessageBuilder {
  public Message getInstance(String title, String text) {
    return new Message(title, text);
  }
}
// Let's turn the POJO into a bean
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
..
@Configuration
public class AppConfig {
  @Bean
  public MessageBuilder messageBuilder() {
    return new MessageBuilder();
  }
}
// Finally, hook it up
..
@Autowired
private MessageBuilder messageBuilder;
..

3、@ComponentScan()
  • @SpringBootApplication注記のmain appがあるパッケージとその下位パッケージを他のパッケージが使用されている場合は、何もしなくてもいいです.SpringBootは自動的に他のパッケージを
  • スキャンします.
  • beanが存在するパッケージがmain appのパッケージとその下位パッケージにない場合は、@ComponentScan注釈を手動で追加し、そのbeanが存在するパッケージ
  • を指定する必要があります.
  • @component注記は、クラスを作成する必要がある場合に、この注記されたクラスが候補クラスであることを示すクラスで使用されます.手を挙げるようです.
  • @ComponentScanは、指定されたパケットの下にあるクラスをスキャンするために使用されます.どんな手を挙げたかを見るようです.