注解方式

注解的优势:简化配置。减少配置。
一般在工作中:使用注解替换部分配置,但是一般使用注解+配置的混合模式。

配置多了,会觉得配置麻烦。
注解多了,会觉得注解麻烦。(一般不能替代所有的配置)
注解可以替代部分的配置。

注解的不足:注解是直接写在java文件中的。.java ->.class
修改注解,需要重新编译。重新打包。就有新的版本。有新的版本。就需要走测试流程。(走流程)

注解开发:
1,引入约束: spring-context
部分替换配置方案
使用统一的模板(拷贝applicationContext.xml)

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">




2,添加注解
@Component(value="userService")组件:作用在类上-- 相当于在XML的配置方式中 也就是创建了对象

创建对象的配置方式:

注解方式:
@Component(value=”id的名称”)

@Component的三个衍生注解
@Controller -- 作用在WEB层(学习 SpringMVC使用)
@Service -- 作用在业务层
@Repository -- 作用在持久层
这三个注解是为了让标注类本身的用途清晰

属性注入的注解
@Value -- 用于普通类型,可以给字段、set方法注解
主要是字符串,集合属性不可以。

对象注入
@Autowired -- 默认按类型进行自动装配
@Qualifier --强制使用名称注入,在Autowired基础上添加

3,配置中开启组件扫描

这样是扫描com.qianfeng包下所有的内容

开发流程:
第一步:持久层替换

@Repository("userDao")
public class UserDaoImpl implements UserDao {
@Override
public void addUser() {
Log.info("我是新添加的用户");
}
}

第二步:服务层替换

@Service("userService")
public class UserServiceImpl implements UserService {
@Value("张颖豪")
private String name;
@Qualifier("userDao")
@Autowired
private UserDaoImpl userDao;

@Override
public void addUser() {
    Log.info("我在service中"+name);
    userDao.addUser();
}

}

第三步:注解扫描
注意有多个包的情况:


作用在类上的注解:@Component创建对象
作用在属性上的注解:@Value给属性赋值(仅支持简单属性赋值)
引用对象:@Autowired
注解生效必须扫描:指定某个包下面的所有类

测试方法如下所示 :

@Test
public void testUserService(){
    ClassPathXmlApplicationContext classPathXmlApplicationContext=new         
                              ClassPathXmlApplicationContext("applicationContext.xml");
             UserServiceImpl userService = (UserServiceImpl) 
             classPathXmlApplicationContext.getBean("userService");


              userService.addUser();
}

输出结果如下:


image.png

你可能感兴趣的:(注解方式)