Spring使用注解管理Bean

引入lib包

Spring使用注解管理Bean_第1张图片

Spring对Bean管理的常用注解

@Component组件(作用在类上)

Spring中提供了@Component的三个衍生注解:(功能在目前为止是一致的)

@Controller WEB层

@Service 业务层

@Repository 持久层

属性注入的注解:(使用注解注入的方式,可以不用提供set方法)

@Value  用于注入普通类型

@Autowired  自动装配

        默认按照类型装配

@Qualifier   强制使用名称注入

@Resource   默认按照名称注入,当找不到名称匹配时才会按照类型装配       

Bean的作用范围注解

@Scope

        常用:

        singleton-单例

        prototype-多例

Bean的生命周期注解配置

@PostConstruct  相当于 init-method

@PreDstroy  相当于 destroy-method

Spring的Bean管理的方式的比较

Spring使用注解管理Bean_第2张图片

使用注解开发

创建user

Spring使用注解管理Bean_第3张图片

创建user接口和接口实现类

给接口实现类加入注解

Spring使用注解管理Bean_第4张图片

在applicationContext.xml中开启扫描

要扫描多个就使用(,)在继续写

创建service接口和接口实现类

使用@Autowired将userDao接口注入进来

Spring使用注解管理Bean_第5张图片

测试

Spring使用注解管理Bean_第6张图片

你可能感兴趣的:(spring,java,后端)