@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);
网友评论