SpringBoot工作常用注解总结

一、SpringBoot

controller层:
    0@Component
    	@Component 泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。

	1@Controller
		@Controller 用来响应页面,表示当前的类为控制器。

	2@RestController
		@RestController@ResponseBody@Controller的结合
		表明当前类是控制器且返回的是一组数据,不是页面

	3@Autowired
		这个注解的作用是将其他的类,接口引入,类似于之前的类的初始化等,用这个注解,类中或接口的方法就可以直接调用了。

	4@RequestMapping
		当前台界面调用Controller处理数据时候告诉控制器怎么操作。
    	@RequestMapping(/path”)表示该控制器处理所有“/path”的URL请求。RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。
		作用:URL映射。
    	@RequestMapping六个属性:
            params:指定request中必须包含某些参数值,才让该方法处理。
            headers:指定request中必须包含某些指定的header值,才能让该方法处理请求。
            value:指定请求的实际地址,指定的地址可以是URI Template模式。
            method:指定请求的method类型,GET、POST、PUT、DELETE等。
            consumes:指定处理请求的提交内容类型(Content-Type),如application/json,text/html。
            produces:指定返回的内容类型,仅当request请求头中的Accept类型中包含该指定类型才返回。

	5@GetMapping
		@RequestMapping(method = RequestMethod.GET)的简写
		作用:对应查询,表明是一个查询URL映射

	6@PostMapping
		@RequestMapping(method = RequestMethod.POST)的简写
		作用:对应增加,表明是一个增加URL映射

	7@PutMapping
		@RequestMapping(method = RequestMethod.PUT)的简写
		作用:对应更新,表明是一个更新URL映射

	8@DeleteMapping
		@RequestMapping(method = RequestMethod.DELETE)的简写
	
    9@PathVariable
    	URI模板变量,这里指uri template中variable(路径变量),不含queryString部分
    	当使用@RequestMapping URI template 样式映射时, 即 someUrl/{paramId},这时的paramId可通过 @Pathvariable注解绑定它传过来的值到方法的参数上。
    	示例代码:
    	@RestController
        @RequestMapping("/users")
        public class UserAction {
            @GetMapping("/{id}")
            public Result getUser(@PathVariable int id) {
                return ResultUtil.successResult("123456");
            }
        }
		上面代码把URI template 中变量 ownerId的值和petId的值,绑定到方法的参数上。若方法参数名称和需要绑定的uri template中变量名称不一致,需要在@PathVariable("name")指定uri template中的名称。

	10@RequestParam
		获取请求参数的值,请求Url必须带参数,例如:localhost:8080/hello?id=1000
        示例代码:
        @RestController
        public class HelloController {
            @RequestMapping(value="/hello",method= RequestMethod.GET)
            public String sayHello(@RequestParam("id") Integer id){
                return "id:"+id;
            }
        }
		在浏览器中输入地址: localhost:8080/hello?id=1000 ,可以看到如下的结果:id:1000 
        当我们在浏览器中输入地址: localhost:8080/hello?id  ,即不输入id的具体值,此时返回的结果为null。具体测试结果如下:id:null 
		但是,当我们在浏览器中输入地址: localhost:8080/hello  ,即不输入id参数,则会报如下错误:whitelable Error Page错误。

    11@RequestBody
		主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的);
        GET方式无请求体,所以使用@RequestBody接收数据时,前端不能使用GET方式提交数据,而是用POST方式进行提交。
        在后端的同一个接收方法里,@RequestBody@RequestParam()可以同时使用,@RequestBody最多只能有一个,而@RequestParam()可以有多个。
        RequestBody接收的是请求体里面的数据;而RequestParam接收的是请求Url地址key-value里面的参数。
        示例代码:
        @PostMapping("/show")
        public String show(@RequestBody Person person, @RequestParam("token") String token) {
			return "id:"+person.getId()+";name:"+person.getName()+";token:"+token;
		}

    10@RequestHeader
		@RequestHeader注解,可以把Request请求header部分的值绑定到方法的参数上。
        示例代码:
        // Request 的header部分
        Accept:text/html,application/xhtml+xml,application/xml;
        Accept-Encoding:gzip, deflate, br
        Accept-Language:zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7
        Cache-Control:max-age=0
        Connection:keep-alive
        Host:localhost:8080
        Upgrade-Insecure-Requests:1
        User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36
		
		@GetMapping("/getRequestHeader")
        public Result getRequestHeader(@RequestHeader("Accept-Encoding") String encoding) {
            return ResultUtil.successResult(encoding);
        }
		上面的代码,把request header部分的 Accept-Encoding的值,绑定到参数encoding上。
		
service层:
	1@service
		用于标注业务层组件

    2@Transactional
        声明式事务管理,接口实现类或接口实现方法上,而不是接口类中。
        访问权限:
            @Transactional 注解只能应用到 public 方法才有效
            Spring 只会回滚运行时、未检查异常(继承自 RuntimeException 的异常)或者 Error
        错误使用
            接口中A、B两个方法,A无@Transactional标签,B有,上层通过A间接调用B,此时事务不生效
            接口中异常(运行时异常)被捕获而没有被抛出
		
dao层:
	1@Repository
		是用来注解接口,@Repository注解可以标记在任何的类上,用来表明该类是用来执行与数据库相关的操作(即dao对象),并支持自动处理数据库操作产生的异常

Java配置:
	1@Configuration@Bean
		可理解为用spring的时候xml里面的<beans>标签,用@Configuration注解该类,等价与XML中配beans
		@Bean是一个方法级别上的注解,主要用在@Configuration注解的类里,也可以用在@Component注解的类里。添加的bean的id为方法名
		例如:
		@Configuration    
		public class ExampleConfiguration {    
		    
		    @Value("com.mysql.jdbc.Driver")    
		    private String driverClassName;    
		    
		    @Value("jdbc://xxxx.xx.xxx/xx")    
		    private String driverUrl;    
		    
		    @Value("${root}")    
		    private String driverUsername;    
		    
		    @Value("123456")    
		    private String driverPassword;    
		    
		    @Bean(name = "dataSource")    
		    public DataSource dataSource() {    
		        BasicDataSource dataSource = new BasicDataSource();    
		        dataSource.setDriverClassName(driverClassName);    
		        dataSource.setUrl(driverUrl);    
		        dataSource.setUsername(driverUsername);    
		        dataSource.setPassword(driverPassword);    
		        return dataSource;    
		    }    
		    
		    @Bean    
		    public PlatformTransactionManager transactionManager() {    
		        return new DataSourceTransactionManager(dataSource());    
		    }    
		    
		}  
		这样,在项目中
        @Autowired
		private DataSource dataSource;的时候,这个dataSource就是我们在ExampleConfiguration中配的DataSource。
	2@ConfigurationProperties
		将配置文件中的参数映射成一个对象,通过prefix来设定前缀,然后将后面的和对象的属性名一致就能实现注入(当然这个对象需要注入的属性需要提供get和set方法 - - - 因为spring底层其实就是通过反射调用该对象的set方法)
        实例:
        @ConfigurationProperties(prefix = “spring.datasource.test1”)
        public class Datasource1 {
            private String url;
            private String username;
            private String password;
            get - - set方法
        }
        application.properties:
        spring.datasource.test1.url=jdbc:mysql://localhost:3307/multipledatasource1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
        spring.datasource.test1.username=root
        spring.datasource.test1.password=root
        spring.datasource.test1.driver-class-name=com.mysql.cj.jdbc.Driver
bean实例
	1@Autowired:自动导入依赖的bean,把配置好的Bean拿来用,完成属性、方法的组装,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作,当加上(required=false)时,就算找不到bean也不报错。

	2@Qualifier:当有多个同一类型的Bean时,可以用@Qualifier(“name”)来指定,与@Autowired配合使用,@Qualifier限定描述符除了能根据名字进行注入,也能进行更细条件的指定。

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

	4@Resource(name=”name”,type=”type”):没有括号内内容的话,默认byName。与@Autowired干类似的事。

	5@Import:用来导入其他配置类。

	6@ImportResource:用来加载xml配置文件。

	7@Value:注入application.properties配置的属性的值。

二、JPA注解

1、@Entity:@Table(name=""):表明这是一个实体类。这两个注解一般一块使用,但是如果表名和实体类名相同的话,@Table可以省略。

2、@MappedSuperClass:用在确定是父类的entity上,父类的属性子类可以继承。

3、@NoRepositoryBean:一般用作父类的repository,有这个注解,spring不会去实例化该repository。

4、@Column:如果字段名与列名相同,则可以省略。

5、@Id:表示该属性为主键。

6、@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = “repair_seq”):表示主键生成策略是sequence(可以为Auto、IDENTITY、native等,Auto表示可在多个数据库间切换),指定sequence的名字是repair_seq。

7、@SequenceGeneretor(name = “repair_seq”, sequenceName = “seq_repair”, allocationSize = 1):name为sequence的名称,sequenceName为数据库的sequence名称,两个名称可以一致。

8、@Transient:表示该属性并非一个到数据库表的字段的映射,ORM框架将忽略该属性。

9、@JsonIgnore:作用是json序列化时将Java bean中的一些属性忽略掉,序列化和反序列化都受影响。

10、@JoinColumn(name="loginId"):一对一:本表中指向另一个表的外键。一对多:另一个表指向本表的外键。

11、@OneToOne、@OneToMany、@ManyToOne:对应hibernate配置文件中的一对一,一对多,多对一。

三、功能型注解

1@SpringBootApplication:启动注解,@SpringBootApplication是一个复合注解,包括@ComponentScan,	和@SpringBootConfiguration@EnableAutoConfiguration
	@SpringBootConfiguration继承自@Configuration,二者功能也一致,标注当前类是配置类,并会将当前类内声明的一个或多个以@Bean注解标记的方法的实例纳入到srping容器中,并且实例名就是方法名。
	@EnableAutoConfiguration的作用启动自动的配置,@EnableAutoConfiguration注解的意思就是Springboot根据你添加的jar包来配置你项目的默认配置,比如根据spring-boot-starter-web ,来判断你的项目是否需要添加了webmvc和tomcat,就会自动的帮你配置web项目中所需要的默认配置。在下面博客会具体分析这个注解,快速入门的demo实际没有用到该注解。
	@ComponentScan,扫描当前包及其子包下被@Component@Controller@Service@Repository注解标记的类并纳入到spring容器中进行管理。是以前的<context:component-scan>(以前使用在xml中使用的标签,用来扫描包配置的平行支持)。

2@ServletComponentScan:在SpringBootApplication上使用@ServletComponentScan注解后,Servlet、Filter、Listener可以直接通过@WebServlet@WebFilter@WebListener注解自动注册,无需其他代码。

3@MapperScan("com.Vm.server")@MapperScan注解只会扫描包中的接口,不会扫描类,扫描指定包中的接口

4@EnableScheduling@Scheduled:定时任务。@EnableScheduling这个注解需要加在启动类上,表示支持定时任务。
	实例:
    @EnableScheduling
    public class ScheduledTasks {
        @Scheduled(fixedRate = 1000 * 30) //每30秒执行一次
        @Scheduled(cron = "0 */1 *  * * * ") //在固定时间执行
        // 详细参考:https://www.cnblogs.com/domi22/p/9418433.html
        public void reportCurrentTime(){
            System.out.println ("Scheduling Tasks Examples: The time is now " + dateFormat 			().format (new Date ()));
        }
    }

@EnableConfigurationProperties:将带有@ConfigurationProperties注解的类注入为Spring容器的Bean。如果使用了@ConfigurationProperties但是没有在启动类上增加这个注解,则@ConfigurationProperties将不起作用。

5、全局异常处理
	@ControllerAdvice:统一处理异常。
	@ExceptionHandler(Exception.class):用在方法上面表示遇到这个异常就执行以下方法。
    
6@Async@EnableAsync:其中@Async表示这个方法为异步方法;@EnableAsync这个注解需要加在启动类上,表示支持异步操作;如果不加,则@Async将不起作用。
	实例:
    @RestController
    public class AsyncController {
        @Autowired
        private AsyncService asyncservice;

        @RequestMapping("/asyncTest.do")
        public String asyncTest() {
            System.out.println("############asyncTest############");
            System.out.println("############a############");
            asyncservice.test();
            System.out.println("############b############");
            return "success";
        }

        @RequestMapping("/asyncTest2.do")
        public String asyncTest2() {
            System.out.println("############asyncTest2############");
            System.out.println("############a############");
            asyncservice.test2();
            System.out.println("############b############");
            return "success";
        }

        @RequestMapping("/asyncTest3.do")
        public String asyncTest3() {
            System.out.println("############asyncTest3############");
            System.out.println("############a############");
            asyncservice.test3();
            System.out.println("############b############");
            return "success";
        }
    }

    @Service
    public class AsyncService {

        public void test() {
            System.out.println("############c############");
            for (int i = 0; i < 5; i++) {
                System.out.println(i);
            }
            System.out.println("############d############");
        }

        @Async
        public void test2() {
            System.out.println("############c############");
            for (int i = 0; i < 5; i++) {
                System.out.println(i);
            }
            System.out.println("############d############");
        }

        /**
         * @Async就相当于另起一个线程
         */
        public void test3() {
            new Thread() {
                @Override
                public void run() {
                    System.out.println("############c############");
                    for (int i = 0; i < 5; i++) {
                        System.out.println(i);
                    }
                    System.out.println("############d############");
                }
            }.start();
        }
    }
	实验结果是: 
        asyncTest.do输出为: acdb; 
		asyncTest2.do输出为: abcd; 
		asyncTest3.do 输出为: abcd;
	所以简单来说:@Async就相当于另起一个线程。

四、Mybatis

//Mapper中的namespace用于绑定Dao接口的,即面向接口编程。
//namespace:一般是dao接口所在的路径+接口名称
<mapper namespace="com.VmService.dao.IBlackDao">

//resultMap属性:type为java实体类;id为此resultMap的标识。
//id和result标签是最简单的映射,id为主键映射;result其他基本数据库表字段到实体类属性的映射。
<resultMap id="BlackBean" type="com.VmService.model.BlackBean">
    <id column="ID" property="id"/>
    <id column="IM" property="im"/>
</resultMap>

//进行SQL语句查找
<select id="selectAllBlackList" resultMap="BlackBean">
    SELECT
		id as id,
		im as im,
	FROM
		t_blacklist t1 
	ORDER BY
		id DESC
</select>
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值