Spring常用注解

使用注解,可以大大提高开发效率!

 


一、准备工作

xml配置:

  配置扫描后,spring才会去扫描指定包下的注解生效。

    <!--扫描可能存在spring注解的包-->
    <context:component-scan base-package="com.lurenjia"></context:component-scan>

二、常用注解

1、配置一个bean对象,默认id为类的首字母小写

  Component、Service(用于业务层实现类)、Repository(数据访问层实现类)、Controller(控制器类)

@Component
public class Client {}

2、配置一个属性为自动注入

  2.1 引用类型的属性

    2.1.1 Resource,Java中的注解,默认按照byName来注入,若没有对应Name,则使用byType。

    2.1.2 Autowired,默认按照byType进行注入。

  2.2 基本类型的数据注入

public class Clients {
    //使用配置文件中的key来注入
    @Value("${user.name}")
    public String name;

    //使用常量注入
    @Value("18")
    private int age;
}

2、配置一个切点

  Pointcut

@Component
public class Client {
    @Pointcut("execution(* com.lurenjia.test.Client.sayHi())")
    public void sayHi() throws Exception{
        System.out.println("执行方法");
    }
}

3、配置一个通知类(切面类)

  Aspect

@Aspect
public class TestAspectjAdvice {}

4、配置一个通知(方法),它必须在通知类中。

  Before、After、Arround...

@Component
@Aspect
public class TestAspectjAdvice {
  
    @Before("com.lurenjia.test.Client.sayHi()")
    public void myBefore(){
        System.out.println("before:前置通知!");
    }
}

 

posted @ 2023-02-28 15:56  在博客做笔记的路人甲  阅读(17)  评论(0编辑  收藏  举报