注册Bean的几个注解
通过下面几个注解可以注册一个bean,bean名都是test,类型为Test
@Controller/@RestController
@Controller
public class Test {
}
语义上使用该注解注释的类是一个controller,是接口的入口。
@Service
@Service
public class Test {
}
语义上使用该注解注释的类属于service,一般将业务代码写在service中。
@Repository
@Repository
public interface Test {
}
一般在使用JPA来进行数据库操作时会用到@Repository注解,用于修饰dao层的接口。
@Component
@Component
public class Test {
}
仅仅是注册了一个bean,没有其他语义上的意义
@Configuration
@Configuration
public class Test {
}
语义上使用该类修饰的注解是一些配置类,如配置redis的序列化方式
@Bean
public class Test {
@Bean
public Test test(){
return new Test();
}
}
相关的其他的几个注解
@ComponentScan
用于设置扫描bean的路径,默认是所修饰类所在包
Spring的启动类上会有一个注解@SpringBootApplication,点进源码可以看到这个注解是被@ComponentScan修饰的,因此Spring项目默认的bean扫描目录就是启动类所在包,这也是为什么创建项目的时候启动类默认在最外层。