Spring Bean
基于Annotation方案配置元数据
org.springframework.context.ApplicationContext
接口类定义容器的对外服务,通过这个接口,可以轻松的从IoC容器中得到Bean对象。在启动Java程序的时候必须要先启动IoC容器。
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
//启动IoC容器,并自动加载 fm.douban 包下的Bean,只要引用了Spring注解的类都可以被加载
ApplicationContext context =
new AnnotationConfigApplicationContext("fm.douban");
AnnotationConfigApplicationContext
这个类的构造函数有两种:
//第一种:根据包名实例化
AnnotationConfigApplicationContext(String ... basePackages);
//第二种:根据自定义包扫描行为实例化
AnnotationConfigApplicationContext(Class clazz);
Spring 官方声明为 Spring Bean 的注解有如下几种:
org.springframework.stereotype.Service
org.springframework.stereotype.Component
org.springframework.stereotype.Controller
org.springframework.stereotype.Repository
只要在类上引用这类注解,都可以被IoC容器加载
@Component
注解通用的Bean注解,其余三个都是扩展自Component
@Service
表示 Service Bean - 主要用于不易变得核心业务逻辑@Controller
作用于 Web Bean - 与前端页面紧密配合,调用@Service
服务读写数据,响应前端请求@Repository
作用于持久化相关 Bean