Spring常见注解
1.
@Jsonlgnore
作用:在json序列化的时候将pojo中的一些属性忽略掉,标记在属性或者方法上面,返回的json数据集不包含该属性。
@Table(name = "tb_user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;// 用户名
@JsonIgnore
private String password;// 密码
private String phone;// 电话
private Date created;// 创建时间
@JsonIgnore
private String salt;// 密码的盐值
//TODO add getter setters
}
2.@Id
标注用于申明一个实体类的属性映射为数据库的主键列,该属性通常置于属性申明语句之前,可与申明语句同行,也可写在单独行上。
3.@GeneratedValue
:用于标注主键的生成策略,通过strategy 属性指定。默认情况下,JPA 自动选择一个最适合底层数据库的主键生成策略:SqlServer对应identity,MySQL 对应 auto increment。
在javax.persistence.GenerationType中定义了以下几种可供选择的策略:
①IDENTITY:采用数据库ID自增长的方式来自增主键字段,Oracle 不支持这种方式;
②AUTO: JPA自动选择合适的策略,是默认选项;
③SEQUENCE:通过序列产生主键,通过@SequenceGenerator 注解指定序列名,MySql不支持这种方式
④TABLE:通过表产生主键,框架借由表模拟序列产生主键,使用该策略可以使应用更易于数据库移植。
@Table(name = "tb_user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;// 用户名
@JsonIgnore
private String password;// 密码
private String phone;// 电话
private Date created;// 创建时间
@JsonIgnore
private String salt;// 密码的盐值
//TODO add getter setters
}
4. @EnableDiscoveryClient 和@EnableEurekaClient
要想将一个微服务注册到 Eureka Server(或其他服务发现组件,例如Zookeeper、Consul等),Eureka 2.0闭源之后,Consul 慢慢会成为主流。
只需:
- 添加Eureka Client(或其他服务发现组件的Client)依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
- 写注解:在启动类上添加注解
@EnableDiscoveryClient
或@EnableDiscoveryClient
@EnableDiscoveryClient
@SpringBootApplication
public class ProviderUserApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderUserApplication.class, args);
}
}
- 写配置
server:
port: 8087
spring:
application:
name: auth-service
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
registry-fetch-interval-seconds: 10
instance:
lease-renewal-interval-in-seconds: 5 # 每隔5秒发送一次心跳
lease-expiration-duration-in-seconds: 10 # 10秒不发送就过期
注:
① 从Spring Cloud Edgware开始,@EnableDiscoveryClient 或@EnableEurekaClient 可省略。只需加上相关依赖,并进行相应配置,即可将微服务注册到服务发现组件上。
② 两者之间的不同点:@EnableEurekaClient只适用于Eureka作为注册中心,@EnableDiscoveryClient 可以是其他注册中心。
5. @EnableFeignClients
启用feign
客户端;
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class LeyouAuthApplication {
public static void main(String[] args) {
SpringApplication.run(LeyouAuthApplication.class, args);
}
}
- 1.
@PostConstruct
作用:在构造方法执行之后执行该方法,能够初始化一些变量或者需要执行一些不需要自己执行的操作的时候。
@PostConstruct
public void init(){
try {
File pubKey = new File(pubKeyPath);
File priKey = new File(priKeyPath);
if (!pubKey.exists() || !priKey.exists()) {
// 生成公钥和私钥
RsaUtils.generateKey(pubKeyPath, priKeyPath, secret);
}
// 获取公钥和私钥
this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
} catch (Exception e) {
logger.error("初始化公钥和私钥失败!", e);
throw new RuntimeException();
}
}
持续更新。。。