Spring常用的的注解对应xml配置详解
@Component(value="")注解:组件
- 标记在类上,也可以放在接口上
- 注解作用:把AccountDao实现类对象交由Spring IOC容器管理
相当于XML配置文件中的Bean标签
<bean id="userAnnonMapper" class="com.spring.mapper.UserAnnonMapperImpl"></bean>
- 注解Value属性:相当于bean标签id,对象在IOC容器中的唯一标识,可以不写,默认值是当前类首字母缩写的类名。注入时需要注意此名称!!。
- 三个衍射注解分别是:@Controller,@Service,@Repository。
作用与@Component注解一样
设计初衷增加代码的可读性,体现在三层架构上
@Controller一般标注在表现层
@Service一般标注在业务层
@Repository一般 标注在持久层
注意:此注解必须搭配扫描注解使用
@Configuration
@ComponentScan("com.*")
public class SpringConfig{}
或 XML配置
<context:component-scan base-package="com.*"></context:component-scan>
进行注解扫描。
@Autowired注解:byType自动注入
- 标记在成员变量或set方法上
- 注解作用:自动将ioc容器中的对象注入到当前的成员变量中。
默认按照变量数据类型注入,如果数据类型是接口,注入接口实现类。
相当于XML配置文件中的property标签
<property name="accountDao" ref="accountDao"/>
- 按照变量的数据类型注入,它只能注入其他的bean类型
- 注意事项:
成员变量的接口数据类型,有多个实现类的时候,要使用bean的id注入,否则会报错。
Spring框架提供的注解
必须指定Bean的id,使用@Qualifier的注解配合,@Qualifier注解的value属性指定bean的id
举例
@Component("userAnnonService02")
public class UserAnnonServiceImpl01 implements UserAnnonService {} @Component("userAnnonService01")
public class UserAnnonServiceImpl02 implements UserAnnonService {}
使用需要注意,因为一个接口被两个实现类实现,所以根据属性已经失效了使用@Qualifier选择要注入的实现类
public class Test{ @Autowired @Qualifier("userAnnonService01") UserAnnonService userAnnonService;
}
其他补充
<bean id="userService" class="com.spring.service.UserServiceImpl"> <property name="userMapper" ref="userMapper"></property>
</bean> <bean id="userMapper" class="com.spring.mapper.UserMapperImpl"></bean>
等价于注解开发的
@Component("userService")
public class UserServiceImpl implements UserService { @Autowired UserAnnonMapper userAnnonMapper;
}@Component("userAnnonMapper")
public class UserMapperImpl implements UserMapper {}
这里是我认为初学者比较容易搞混的地方。
@Resource(name="") byName注解(jdk提供)
- 标记在成员变量或set方法上
- 注解作用:相当于@Autowired的注解与@Qualifier的注解合并了,直接按照bean的id注入。
相当于XML配置文件中的property标签
<property name="accountDao" ref="accountDao"/>
- name属性:指定bean的id
- 如果不写name属性则按照变量数据类型注入,数据类型是接口的时候注入其实现类。如果定义name属性,则按照bean的id注入。
- Java的JDK提供本注解。
@Configuration注解
标记在类上
注解作用:作用等同于beans.xml配置文件,当前注解声明的类中,编写配置信息,所以我们把
@Configuration声明的类称之为配置类。
//通过配置xml的获取
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
accountService = ac.getBean("accountService ");
//通过配置类,初始化Spring的ioc容器
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
//获取AccountService接口的实现类对象
accountService = ac.getBean(AccountService.class);
@Import注解
标记在类上
注解作用:导入其他配置类(对象)
相当于XML配置文件中的标签
<import resource="classpath:applicationContext-dao.xml"/>
引用场景
在配置文件按配置项目时使用xml分层
例如 mvc.xml,dao.xml,service.xml分别配置提高可读性和可维护性,使用 import 引入同一个xml中进行读取。
多个configuration配置类时使用
@Import(配置类.class) 或 @Import({配置类.class,配置类.class}) 参数为数组加载多个配置类
@PropertySource注解
标记在类上
注解作用:引入外部属性文件(db.properties)
相当于XML配置文件中的context:property-placeholder标签
<context:property-placeholder location="classpath:jdbc.properties"/>
@Configuration
@PropertySource({"db.properties"})
public class SpringConfigClass {}
或者
@PropertySource("classpath:db.properties")
@Value注解
标记在成员变量或set方法上
注解作用:给简单类型变量赋值
相当于XML配置文件中的标签
<property name="driverClass" value="${jdbc.driver}"/>
@Bean注解
标记在配置类中的方法上
注解作用:将方法的返回值存储到Spring IOC容器中
相当于XML配置文件中的标签
举例 @PropertySource @Value @Bean 的整合
@Configuration
@PropertySource({"db.properties"})
public class SpringConfigClass { @Value("${jdbc.driver}") private String dataSource; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String userName; @Value("${jdbc.password}") private String passWord; @Bean public DruidDataSource dataSource() { DruidDataSource druidDataSource = new DruidDataSource(); druidDataSource.setDriverClassName(dataSource); druidDataSource.setUrl(url); druidDataSource.setUsername(userName); druidDataSource.setPassword(passWord); return druidDataSource; }
}
等价于 xml
<context:property-placeholder location="classpath*:db.properties"/>
<!--注入 druid-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driver}"></property> <property name="url" value="${jdbc.url}"></property> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property>
</bean>
@ComponentScan(“com.*”)注解
标记在配置类上
相当于XML配置文件中的context:component-scan标签
<context:component-scan base-package="com.spring.annotation" use-default-filters="false"> <context:include-filter type="custom" expression="com.spring.annotation.filter.ColorBeanLoadFilter" /> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Component" />
</context:component-scan>
@Configuration
@ComponentScan
public class SpringConfigClass { }
属性
value:指定要扫描的package; 若value值为空则扫描当前配置类的包以及子包。
includeFilters=Filter[]:指定只包含的组件
excludeFilters=Filter[]:指定需要排除的组件;
useDefaultFilters=true/false:指定是否需要使用Spring默认的扫描规则:被@Component, @Repository, @Service, @Controller或者已经声明过@Component自定义注解标记的组件;
在过滤规则Filter中:
FilterType:指定过滤规则,支持的过滤规则有
ANNOTATION:按照注解规则,过滤被指定注解标记的类;
ASSIGNABLE_TYPE:按照给定的类型;
ASPECTJ:按照ASPECTJ表达式;
REGEX:按照正则表达式
CUSTOM:自定义规则;
value:指定在该规则下过滤的表达式;
扫描指定类文件 @ComponentScan(basePackageClasses = Person.class) 扫描指定包,使用默认扫描规则,即被@Component, @Repository, @Service, @Controller或者已经声明过@Component自定义注解标记的组件; @ComponentScan(value = "com.yibai") 扫描指定包,加载被@Component注解标记的组件和默认规则的扫描(因为useDefaultFilters默认为true) @ComponentScan(value = "com", includeFilters = { @Filter(type = FilterType.ANNOTATION, value = Component.class) }) 扫描指定包,只加载Person类型的组件 @ComponentScan(value = "com", includeFilters = { @Filter(type = FilterType.ASSIGNABLE_TYPE, value = Person.class) }, useDefaultFilters = false) 扫描指定包,过滤掉被@Component标记的组件 @ComponentScan(value = "com", excludeFilters = { @Filter(type = FilterType.ANNOTATION, value = Component.class) }) 扫描指定包,自定义过滤规则 @ComponentScan(value = "com.yibai", includeFilters = { @Filter(type = FilterType.CUSTOM, value = ColorBeanLoadFilter.class) }, useDefaultFilters = true)
举例
// useDefaultFilters = false 关闭默认过滤使用创建的过滤
// value = {UserAllAnnonService.class, UserAllAnnonMapper.class} 只扫描这两个接口的组件注解
@Configuration
@ComponentScan(includeFilters = {@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = {UserAllAnnonService.class, UserAllAnnonMapper.class})},useDefaultFilters = false)
public class SpringConfigClass { }
@EnableAspectJAutoProxy 开启Aop注解支持
对应标签
aop:aspectj-autoproxy/
举例
@Configuration
@ComponentScan
@PropertySource("classpath:db.properties")
@ImportResource({"classpath:beans.xml"})
@EnableAspectJAutoProxy
public class SpringConfigClass {...}
@EnableTransactionManagement 开启注解事务控制
对应xml标签
<tx:annotation-driven/>
@Configuration
@ComponentScan
@PropertySource("classpath:sqlLink.properties")
@ImportResource({"classpath:beans.xml"})
@EnableTransactionManagement
public class SpringConfigClass {...}
@Transactional() 事务处理,加到方法上,开启当前方法的事务支持
常用属性
transactionManager 属性: 设置事务管理器,如果不设置默认是transactionManager。
isolation属性: 设置事务的隔离级别。
propagation属性: 事务的传播行为。
@Override
@Transactional(transactionManager = "transactionManager", isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED)
public Integer saveUser(User user) { Integer integer = userMapper.saveUser(user); return integer;
}
其他注解
@Scope(“prototype”)
标记在类上,配合@Component使用
注解作用:指定对象的作用范围:单例模式(singleton)还是多例模式(prototype)
@PostConstruct、@PreDestroy 生命周期注解
@PostConstruct ==> init-method
举例:
@Component
public class School {@PostConstructpublic void init(){System.out.println("annotation PostConstruct");}
}
<bean id = "school" class="com.abc.model.School" init-method="init"></bean>
@PreDestroy ==> destroy
举例:
@Component
public class School {@PreDestroypublic void destroyMethod(){System.out.println("annotation PostConstruct");}
}
<bean id = "school" class="com.abc.model.School" destroy-method="init"></bean>
@ImportResource({“classpath:beans.xml”})
引入外部配置,此注解适用于配置类和xml配置共同存在
举例
@Configuration
@ComponentScan
@PropertySource("classpath:db.properties")
@ImportResource({"classpath:beans.xml"})
public class SpringConfigClass {...}
对应xml配置
<import resource="beans.xml"></import>
@Aspect 切面
注解作用:当前类的对象,是一个切面类
<aop:config><aop:aspect id="" ref="" /></aop:config>
@Pointcut 切点
@Pointcut("execution(public void com.itheima.service.AccountServiceImpl.save())")
public void pointcut() {}
对应xml
<aop:pointcut id="pointcutService" expression="execution(* com.spring.service.UserServiceImpl.*(..))"/>
@After(“pointcut()”) 后置通知
@AfterThrowing(“pointcut()”) 异常通知
@AfterReturning(“pointcut()”) 最终通知
@Before(“pointcut()”) 前置通知
举例
@Before("pointcut()")
public void beforePrintLog() { System.out.println("方法执行之前,输出日志");
}
对应xml
<aop:before method="beforePrintLog" pointcut-ref="pointcutService"/>
@Around(“pointcut()”) 环绕通知
//要求必须要传递一个参数: ProceedingJoinPoint
@Around("pointcut()")
public void aroundPrint(ProceedingJoinPoint joinPoint) {}
@MapperScan
指定要变成实现类的接口所在的包,然后包下面的所有接口在编译之后都会生成相应的实现类
@MapperScan("com")
Spring常用的的注解对应xml配置详解相关推荐
- mybatis 同名方法_MyBatis(四):xml配置详解
目录 1.我们将 数据库的配置语句写在 db.properties 文件中 2.在 mybatis-configuration.xml 中加载db.properties文件并读取 通过源码我们可以分析 ...
- SpringBoot—整合log4j2入门和log4j2.xml配置详解
关注微信公众号:CodingTechWork,一起学习进步. 引言 对于一个线上程序或者服务而言,重要的是要有日志输出,这样才能方便运维.而日志的输出需要有一定的规划,如日志命名.日志大小,日志分 ...
- JavaWeb web.xml配置详解
参考: XML 教程 Java web之web.xml配置详解 Javaweb三大组件是:Servlet,Filter,Listener. 1.Servlet Servlet作为中转处理的容器,连接了 ...
- Ehcache 中ehcache.xml 配置详解和示例
EhCache 是一个纯Java的进程内缓存框架,具有快速.精干等特点,是Hibernate中默认的CacheProvider. Ehcache是一种广泛使用的开源Java分布式缓存.主要面向通用缓存 ...
- web.xml配置详解
往者不谏 来者可追 写作是最好的社交 新随笔 订阅 web.xml配置详解 Web.xml常用元素<web-app><display-name></display-nam ...
- Java web之web.xml配置详解
什么是web.xml web.xml是web项目的配置文件,一般的web工程都会用到web.xml来配置,方便大型开发.web.xml主要用来配置Filter,Listener,Servlet等.但是 ...
- Maven的settings.xml配置详解
Maven的settings.xml配置详解 1 基本介绍 maven的两大配置文件:settings.xml和pom.xml.其中settings.xml是maven的全局配置文件,pom.xml则 ...
- java web工程web.xml配置详解
转载自:http://blog.csdn.net/believejava/article/details/43229361 这篇文章主要是综合网上关于web.xml的一些介绍,希望对大家有所帮助,也欢 ...
- javaweb:web.xml配置详解
Web.xml详解: 1.web.xml加载过程(步骤) 首先简单讲一下,web.xml的加载过程.当启动一个WEB项目时,容器包括(JBoss.Tomcat等)首先会读取项目web.xml配置文件里 ...
最新文章
- mysql unrecognized_service mysql start出错,mysql启动不了,解决mysql: unrecognized service错误...
- Java Collection框架—List\ set \map 的异同世界
- python爬取小说章节信息用pygame进行数据显示_爬虫不过如此(python的Re 、Requests、BeautifulSoup 详细篇)...
- 【NoSQL】NoSQL入门和概述 - 笔记
- 第三次学JAVA再学不好就吃翔(part101)--IO流
- 三菱d700变频器模拟量控制_三菱Q系列PLC,用CCLink控制变频器正反转和多段速
- 第9章 项目人力资源管理
- 图像函数 imagecreatetruecolor()和imagecreate()的异同点
- vue3 使用echarts
- java pdf 加水印
- recover的用法
- 美团机器学习InAction系列—实例详解机器学习如何解决问题
- 照片文件与计算机系统,照片文件格式怎么修改
- Verilog 中signed和$signed()的用法
- 人体组织平面波超声成像仿真(MATLAB k-Wave仿真)
- k8s创建用户账号——User Account
- iOS和Android使用同一个二维码自动跳转不同下载页面链接(附生成二维码地址方法)
- 学习JavaScript
- 常见的限流算法与实现
- 虚幻4 读取Json文件数据
热门文章
- java gc log调优_Java 开启 gc 日志
- 数字编码电位器c语言,数字电位器——x9c104
- 我感觉这个书上的微信小程序登陆写得不好
- 【springboot】之自动配置原理
- 机器学习的简单逻辑回归的Advanced Optimization
- C++ map注意事项
- windows下gvim中文乱码解决方案
- ScrollView中使用ListView
- C++中的三种继承public,protected,private(转)
- c++ 箭头符号怎么打_焊接图纸符号标注图解示例,焊接符号标注实例及方法