Spring注解开发 - bean定义、@Component注解的衍生注解、纯注解开发
Spring注解开发
- 一、注解开发定义bean
-
-
- 1、xml配置文件中不再使用bean标签定义bean,仅仅使用context标签开启组件扫描
- 2、使用@Component定义bean,代替复杂的xml文件配置
- 3、测试代码
- 4、测试结果
-
- 二、@Component注解的衍生注解
-
-
- 衍生注解一:@Repository
-
-
- 举例
-
- 衍生注解二:@Service
-
-
- 举例
-
- 衍生注解三:@Controller
-
-
- 举例
-
-
- 三、纯注解开发
-
-
- 1、定义SpringConfig配置类
- 2、加载配置类容器
-
一、注解开发定义bean
1、xml配置文件中不再使用bean标签定义bean,仅仅使用context标签开启组件扫描
<context:component-scan base-package="qdxorigin.dao"/>
- "component-scan"翻译过来就是组件扫描的意思,使用"base-package"属性配置需要通过扫描加载bean的包名。
2、使用@Component定义bean,代替复杂的xml文件配置
@Component("beanDao") // @Componentpublic class BeanDaoImpl implements BeanDao { public void save() { System.out.println("beanDao save..."); }}
- @Component(“beanDao”)这条语句就相当于xml文件中的
<bean id="beanDao" class="dao.impl.BeanDaoImpl"/>
括号里的内容就相当于id属性值
- @Component 也可以不指定名,在获取bean对象时使用按类型获取的方式
BeanDao bean = context.getBean(BeanDao.class);
不清楚bean获取方式的小伙伴可以点击查看文章"三种获取bean的方式"。
3、测试代码
public class App { public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); BeanDao beanDao = (BeanDao) context.getBean("beanDao"); // BeanDao beanDao = context.getBean(BeanDao.class); System.out.println(beanDao); }}
4、测试结果
dao.impl.BeanDaoImpl@58a90037
- 成功打印出了地址值
二、@Component注解的衍生注解
衍生注解一:@Repository
该注解用于数据访问层的bean定义,数据访问层也就是我们常写的dao层、mapper层。
举例
@Repository("beanDao")// @Repositorypublic class BeanDaoImpl implements BeanDao { public void save() { System.out.println("beanDao save..."); }}
衍生注解二:@Service
该注解用于业务逻辑层的bean定义,即service层。
举例
@Service("beanService")// @Servicepublic class BeanServiceImpl implements BeanService { public void save() { System.out.println("bean service save..."); }}
衍生注解三:@Controller
该注解用于表现层,控制层的bean定义,即controlle层等。
举例
@Controller("beanController")// @Controllerpublic class BeanController {}
三、纯注解开发
Spring3.0开启了纯注解开发模式,提倡使用Java类来代替xml配置文件,使用纯注解开发在极大程度上提升了开发人员的开发效率。
1、定义SpringConfig配置类
@Configuration@ComponentScan("qdxorigin.dao")public class SpringConfig {}
- @Configuration 注解用于设置当前类为配置类,作用相当于xml文件中的
<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"></beans>
这么多行代码一个注解就代替了,有没有感觉用注解开发很爽呢?!
- @ComponentScan(“qdxorigin.dao”) 该行代码的作用和xml配置文件中
<context:component-scan base-package="qdxorigin.dao"/>
的作用一样。
- @ComponentScan 注解用于设定扫描路径,该注解只能使用1次,如果有多个需要扫描的包,使用下述方式实现
@ComponentScan({"qdxorigin.dao","qdxorigin.service"})
2、加载配置类容器
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
- 因为使用了纯注解开发,没有了xml文件,自然也不能再使用"ClassPathXmlApplicationContext"的方式加载配置文件。
- 获取bean的方式和之前没有区别,还是可以使用getBean方法进行获取。