@Component , @Service 和 @Controller
@Component 是對 Spring 任意管理 組件的通用刻 板。@Repository ,@Service 和 @Controller 是對更多的特定用例@Component 的專業化,比如,在持久層,服務層和 表現層。因此,你可以使用@Component 注解你的組件類,但是使用@Repository, @Service 或@Controller 注解來替代的話,那么你的類更合適由工具來處理或和不同的方面相關聯。
<context:component-scan base-package="org.example"/>
自動檢測包下的類并注冊對應的Bean。可以用逗號分隔兩個包
<context:component-scan base-package="com.example.cors,com.example.Test"/>
@Configration和@Bean
這兩個注解用于像xml那樣注冊bean和bean之間的關系,缺點在于需要單獨的類去維護
@Configuration
public class AppContext {
@Bean
public Course course() {
Course course = new Course();
course.setModule(module());
return course;
}
@Bean
public Module module() {
Module module = new Module();
module.setAssignment(assignment());
return module;
}
@Bean
public Assignment assignment() {
return new Assignment();
}
}
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppContext.class);