文章目录
- 前言
- 叙述
- 注解模式
- 实现层
- xml配置文件
- 测试类
- 其他注解
- 总结
前言
在之前的博客中,小咸儿使用xml配置的方式,让IOC容器实现对象的创建以及依赖的功能。接下来使用另一种更为简单的方式——注解
叙述
注解模式
之前小咸儿已经写过如何通过xml文件来创建对象,接下来直接说明注解的使用方式。
实现层
在创建完接口层后,接下来就是需要自己去创建一个具体实现类:UserServiceImpl
package annotation;
import org.springframework.stereotype.Component;
/**
* IOC示例:具体实现类
* @author Phyllis
* @date 2019年7月18日17:36:38
*/
@Component("userServiceId")
public class UserServiceImpl implements UserService {
/**
* 通过用户ID查询用户信息
* @Param userId
* @return
*/
public void selectByUserId(String userId) {
if(userId == '123'){
System.out.println("此用户不存在");
}
}
}
但是不同的是,这里需要添加一个注解@Component,引自org.springframework.stereotype.Component。
作用:
@Component 取代 <bean class="">
@Component("id") 取代 <bean id="" class="">
除此之外呢,在web开发中,还提供了3个@Component注解的衍生注解,功能与其一样,可以取代<bean class="">
使用。在这个实例中使用的上述注解。
@Repository :dao 层
@Service:service 层
@Controller:web 层
xml配置文件
虽然我们使用了注解,但是我们也需要让程序再启动时能够读取这个注解,这样才能发挥这个注解的作用,所以还需要在xml配置文件中,写明需要去扫描那些配置了注解的包
仍然在上一次的配置文件中添加配置
接着在配置文件中配置好需要扫描的包
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 配置service
<bean> 配置需要创建的对象
id:用于之后从spring容器获得示例时使用的
class:需要创建实例的全限定类名
-->
<bean id="userServiceId" class="ioc.UserServiceImpl"></bean>
<!--组件扫描,扫描含有注解的类-->
<context:component-scan base-package="annotation"></context:component-scan>
</beans>
测试类
这时候就可以做一个简单的测试了:TestAnnoIoc
package annotation;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestAnnoIoc {
@Test
public void demo01(){
// 从spring容器中获得
// 1、获得容器
String xmlPath = "beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
// 2、获得内容---不需要自己new,都是从spring容器获得
UserService userService = (UserService) applicationContext.getBean("userServiceId");
userService.selectByUserId("123");
}
}
结果: 这个实例仍然能够运行成功,也就是说使用注解+xml配置文件的形式,让注解去帮助我们创建对象。
其他注解
另外,如果在依赖注入时,需要给私有字段设置或者给setter方法设置,该怎么办呢?
接下来就来说明一下,该如何解决:
- 普通值:使用
@Value(“”)
即可 - 引用值:
方式一:按照类型注入:@Autowired
方式二:按照名称注入1:@Autowired 或者 @Qualifier("名称")
方式三:按照名称注入2:@Resources("名称")
总结
这里只是一个简单的注解使用过程