使用spring,首先就要导入spring的4个核心jar包:beans、core、context、expression
然后,要使用注解,
就要引入 context 的约束 :http://www.springframework.org/schema/context/spring -context.xsd
以及配置注解扫描:<context:component -scan base -package="com.haha.spring.demo"/> 表示:会扫描com.haha.spring.demo包下的所有类中的注解,包括子包
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 使用注解的方式将组件管理到容器中:
1. 在spring的配置文件中开启注解扫描
<context:component-scan: 开始注解扫描
base-package:指定基本包,Spring会扫描指定包以及子包下面所有的类
2. 在各个组件上加上对应的注解
-->
<context:component-scan base-package="com.atguigu.order"></context:component-scan>
</beans>
Spring 中提供 @Component 的三个衍生注解 :( 功能目前来讲是一致的 )
* @Controller :WEB 层
* @Service :业务层
* @Repository :持久层
这三个注解是为了让标类本身的用途清晰, Spring 在后续版本会对其增强 在后续版本会对其增强 在后续版本会对其增强 在后续版本会对其增强
属性注入的解 :( 使用注解入的方式 ,可以不用提供 set 方法 )
@Value :用于注入普通类型 . 给属性赋值
@Autowired :自动装配 :
* 默认按类型进行装配
* 按名称注入: 但是可能会出现不同包下有相同名称的类,此时就会引起冲突,这时就可以附加@Qualifier 强制使用名称注入 .
@Resource 相当于 相当于 : * @Autowired 和@Qualifier 一起使用 .
Bean的作用范围注解
@scope
singleton:单例;默认,如果不添加该注释则为此范围
prototype:多例
使用较多的是singleton,其次是prototype,还有其他的,但是使用不多
Bean的生命周期配置
@PostConstruct :相当于 init -method
@PreDestroy :相当于 destroy -method
XML:结构清晰
注解:开发方便