注解开发IoC
bean配置文件约束头:
<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.xsd">使用注解开发IoC需要使用新的约束头,并且需要使用context:component-scan标签添加扫描的包,如下
<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.xsd">
<context:component-scan base-package="com.oylong"></context:component-scan>
</beans>用于创建对象的注解
等于在xml中配置bean标签
@Component用于把当前类对象存入Spring容器,
value值为bean的id,不写时默认值为当前类名,且首字母改为小写@Controller一般用于表现层
@Service一般用于业务层
@Repository一般用于持久层
以上四个注解的作用于属性都相同,是Spring框架为我们提供明确的使用三层的注释,是我们的三层对象更加清晰
用于注入数据的
等于在bean标签中配置property标签
@Autowrite自动按照类型注入,只要容器中有唯一的bean对象与要注入的类型匹配,就可以注入成功,可以在成员变量上使用,也可以在方法上,不需要写
set方法若有多个bean对象匹配,则会根据要注入的变量的名称去与bean对象的id去匹配
@Qualifier在按照类型注入的基础上,再按照名称注入。给类成员注入时不能单独使用,给方法参数注入时可以
@Resource直接按照bean的id注入,可以独立使用
@Resource(name="???")@Value用于注入基本类型和
String类型的数据value:用于指定数据的指,可以使用Spring的SpEL表达式${表达式}
用于改变作用范围的
等于使用了bean标签的scope属性
@Scope用于指定bean的作用范围
value:指定取值范围,如singleton,prototype。默认为singleton
和生命周期有关的
等于在bena标签中使用的init-method和destory-method
@PreDestory:用于指定销毁方法@PostConstruct:用于指定初始化方法