Spring常用的的注解以及对应xml配置详解

@Component(value="")注解:组件

1. 标记在类上,也可以放在接口上
2. 注解作用:把AccountDao实现类对象交由Spring IOC容器管理
相当于XML配置文件中的Bean标签

<bean id="userAnnonMapper" class="com.spring.mapper.UserAnnonMapperImpl"></bean>

3. 注解Value属性:相当于bean标签id,对象在IOC容器中的唯一标识,可以不写,默认值是当前类
首字母缩写的类名。注入时需要注意此名称!!。
4. 三个衍射注解分别是:@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自动注入

1. 标记在成员变量或set方法上
2. 注解作用:自动将ioc容器中的对象注入到当前的成员变量中。
默认按照变量数据类型注入,如果数据类型是接口,注入接口实现类。
相当于XML配置文件中的property标签

<property name="accountDao" ref="accountDao"/>

3. 按照变量的数据类型注入,它只能注入其他的bean类型
4. 注意事项:
成员变量的接口数据类型,有多个实现类的时候,要使用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提供)

1. 标记在成员变量或set方法上
2. 注解作用:相当于@Autowired的注解与@Qualifier的注解合并了。直接按照bean的id注入。
相当于XML配置文件中的property标签

<property name="accountDao" ref="accountDao"/>

3. name属性:指定bean的id
4. 如果不写name属性则按照变量数据类型注入,数据类型是接口的时候注入其实现类。如果定义
name属性,则按照bean的id注入。
5. 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.yibai", includeFilters = { @Filter(type = FilterType.ANNOTATION, value = Component.class) })
扫描指定包,只加载Person类型的组件
   @ComponentScan(value = "com.yibai", includeFilters = { @Filter(type = FilterType.ASSIGNABLE_TYPE, value = Person.class) }, useDefaultFilters = false)
扫描指定包,过滤掉被@Component标记的组件
   @ComponentScan(value = "com.yibai", excludeFilters = { @Filter(type = FilterType.ANNOTATION, value = Component.class) })
扫描指定包,自定义过滤规则
   @ComponentScan(value = "com.yibai", includeFilters = { @Filter(type = FilterType.CUSTOM, value = ColorBeanLoadFilter.class) }, useDefaultFilters = true

举例

@Configuration
@ComponentScan(
includeFilters
= {@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = {UserAllAnnonService.class, UserAllAnnonMapper.class})},
useDefaultFilters = false) public class SpringConfigClass { }

解释,

useDefaultFilters = false 关闭默认过滤使用创建的过滤  

value = {UserAllAnnonService.class, UserAllAnnonMapper.class} 只扫描这两个接口的组件注解

@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 ==> init-method
@PreDestroy ==> destroy

@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("cn.zys.mapper")
原文地址:https://www.cnblogs.com/xiaozhang666/p/13630121.html