为什么要使用注解方式开发?
使用注解开发就是用来替代xml文件中下面的繁琐的<bean>的配置,提高开发效率
* <bean id="accountService" class="com.leon.service.impl.AccountServiceImpl"
* scope="" init-method="" destroy-method="">
* <property name="" value="" / ref=""></property>
* </bean>
*
在bean.xml中引入新的具有context标签的xml配置文件头部
若要使用注解方式,第一步应告诉spring在创建容器时应扫描的包,需要用到context标签,需要重新引入带有context标签的xml 配置文件头部,这样便可以使用<context-component-scan>标签了
<?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.xsd">
引入新的xml配置文件表头后在bean.xml中使用<context:component-scan base-package="">标签告诉spring创建容器时应扫描的包
<context:component-scan base-package="com.leon.*"></context:component-scan>
spring的常用注解
* 常用注解的分类:
* 用于创建对象的:它们的作用就和在XML文件中编写一个<bean>标签实现的功能是一样的
* @Component:用于把当前类对象存入spring容器中
* :属性value 用于指定bean的id,不写时默认为当前类名的首字母小写
* @Controller: 一般用在表现层
* @Service: 一般用在业务层
* @Repository: 一般用于持久层
* 以上三个注解的作用和属性和Component一样,是spring框架为我们明确三层的使用的注解
* 使我们的三层框架更明确
*
* 用于注入数据的:它们的作用就和在XML配置文件中写一个<property>标签是一样的
* @Autowired:自动按照类型注入,只要容器中有唯一的一个bean对象类型和要注入的变量来类型相匹配,就自动注入
* 出现位置:可以是成员变量上,也可以是方法上
* 如果没有匹配的注解bean类型时报错。
* 如果有多个类型匹配时按照对象名查询已存在bean的id匹配
* @Qualifier:在按照类注入的基础上再按照名称注入。它在给类成员中不能单独使用,但是在给方法参数注入时可以
* :value:用于指定注入bean的id
* @Resource:直接按照bean的id注入,可以独立使用
* :name:用于指定bean的id
* 以上三种注入都只能实现bean类型的注入,不能实现基本类型和String类型的注入
* List集和的注入只能通过xml配置文件的方式来实现
* @Value:用于注入基本类型和String类型的数据:
* :value:用于指定数据的值。它可以使用spring中的spEL(spring的EL表达式 ${表达式})
* 用于改变作用范围的:它们的作用就和在<bean>标签中使用scope属性实现的功能是一样的
* 作用和bean标签中的scope作用是一样的
* @Scope:指定bean的范围
* :value:指定范围的取值(singleton/prototype)
*
* 和生命周期相关的:它们的作用就和在<bean>标签中init-method和destroy-method作用是一样的
* 了解:preDestroy:用于指定销毁方法 PostConstruct:用于指定初始化方法
*/
示例:
@Service注解 声明此类将会注入到核心容器中,value属性对应<bean>中的id属性
@Resource注解 声明会在核心容器中搜索IAccountDao的类型并赋值给成员变量,当容器中与该类型相匹配的bean对象类型多于一个时,name属性用于指定要匹配的bean对象的id
@Value注解 声明注入的基本类型和String类型成员变量的值
@Scope注解 声明核心容器中的对象是单例还是多例
@Scope("singleton")
@Service(value = "accountService")
public class AccountServiceImpl implements IAccountService {
@Resource(name = "accountDao")
private IAccountDao accountDao2;
@Value("Leon")
private String username;
public void SaveAccount() {
System.out.println("username="+username);
accountDao2.saveAccount();
}
}
@Resource指定的成员变量一定也要加载到核心容器中
@Repository
public class AccountDao implements IAccountDao{
public void saveAccount() {
System.out.println("++++");
}