@getter和@setter需要引入哪个依赖
时间: 2023-09-30 16:02:45 浏览: 105
如果你提到的是Java中的注解 @Getter 和 @Setter,它们通常是由Lombok库提供的。Lombok是一个Java库,可以通过注解来自动生成常见的代码,如getter、setter、构造函数等。要使用 @Getter 和 @Setter 注解,你需要在项目中引入Lombok的依赖。下面是一个使用Maven构建工具的示例:
```xml
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
```
当你在类上使用 @Getter 和 @Setter 注解时,Lombok会自动生成对应的getter和setter方法。这样可以简化代码编写,并且提高开发效率。需要注意的是,你在编译代码时需要确保IDE或构建工具已经配置了正确的Lombok插件,以便能够正确处理这些注解。
相关问题
vue3getter和setter
在Vue3中,getter和setter是通过使用属性代理的方式实现的。具体来说,Vue3使用了`Object.defineProperty`方法来对属性进行代理,从而通过`vm.xx`对`vm._data.xx`进行读写操作。在Vue的实例化过程中,会调用`observe`方法来实例化一个`Observe`类,将`vm.xx`由数据属性转变为访问器属性,并设置getter和setter。每个属性的getter都会实例化一个`Dep`类,用于收集依赖,而setter则会通知更新。当数据发生变动时,setter会触发对应属性维护的`dep`的`notify`方法,通知保存在`dep.subs`中的`Watcher`实例进行更新。这样就实现了getter和setter的功能。
然而,`Object.defineProperty`存在一些问题。首先,在`defineReactive`方法中使用getter和setter时,需要遍历递归,并使用闭包存储数据值的副本。当数据量较大时,会导致性能下降。其次,`Object.defineProperty`的代理是针对属性级别的,无法对对象级别进行代理。
为了解决这些问题,Vue3引入了新的代理方式,即`Proxy`。使用`Proxy`可以更灵活地进行属性代理。通过创建一个`Proxy`实例,可以对整个对象进行代理操作。与`Object.defineProperty`相比,`Proxy`可以动态添加和删除属性,并且可以对这些操作做出反应。在控制台修改`Proxy`的值后,页面会自动更新。相比之下,使用`Object.defineProperty`需要在`data`中定义属性并为每个属性调用`Object.defineProperty`方法设置getter和setter,而且无法对delete操作做出反应。
综上所述,Vue3中通过属性代理实现了getter和setter的功能。`Object.defineProperty`是Vue3早期使用的方式,但由于其存在的问题,Vue3后续引入了`Proxy`,使得代码更具有抽象性。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [关于Vue3.x选用proxy放弃访问器属性(setter/getter)的一点理解。](https://blog.csdn.net/weixin_33724059/article/details/91422102)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
springboot security项目 如何封装jwt 及token 其中数据表为package com.aokace.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.io.Serializable; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Getter; import lombok.Setter; /** * <p> * * </p> * * @author aokace * @since 2023-05-23 */ @Getter @Setter @TableName("user") @ApiModel(value = "User对象", description = "") public class User implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "userid", type = IdType.AUTO) private Integer userid; @TableField("authority") private String authority; @TableField("role") private String role; @TableField("username") private String username; @TableField("password") private String password; }
首先需要引入相关的依赖,包括JWT和Spring Security的依赖:
```
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
然后创建一个JwtTokenUtil类来实现JWT的签发和验证功能:
```java
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Component
public class JwtTokenUtil {
private static final String CLAIM_KEY_USERNAME = "sub";
private static final String CLAIM_KEY_CREATED = "created";
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.expiration}")
private Long expiration;
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
claims.put(CLAIM_KEY_CREATED, new Date());
return generateToken(claims);
}
public String getUsernameFromToken(String token) {
String username;
try {
Claims claims = getClaimsFromToken(token);
username = claims.getSubject();
} catch (Exception e) {
username = null;
}
return username;
}
public Date getCreatedDateFromToken(String token) {
Date created;
try {
Claims claims = getClaimsFromToken(token);
created = new Date((Long) claims.get(CLAIM_KEY_CREATED));
} catch (Exception e) {
created = null;
}
return created;
}
public Date getExpirationDateFromToken(String token) {
Date expiration;
try {
Claims claims = getClaimsFromToken(token);
expiration = claims.getExpiration();
} catch (Exception e) {
expiration = null;
}
return expiration;
}
public boolean isTokenExpired(String token) {
Date expiration = getExpirationDateFromToken(token);
return expiration.before(new Date());
}
public String refreshToken(String token) {
String refreshedToken;
try {
Claims claims = getClaimsFromToken(token);
claims.put(CLAIM_KEY_CREATED, new Date());
refreshedToken = generateToken(claims);
} catch (Exception e) {
refreshedToken = null;
}
return refreshedToken;
}
public boolean validateToken(String token, UserDetails userDetails) {
String username = getUsernameFromToken(token);
return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
}
private Claims getClaimsFromToken(String token) {
Claims claims;
try {
claims = Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
} catch (Exception e) {
claims = null;
}
return claims;
}
private String generateToken(Map<String, Object> claims) {
Date expirationDate = new Date(System.currentTimeMillis() + expiration * 1000);
JwtBuilder builder = Jwts.builder()
.setClaims(claims)
.setExpiration(expirationDate)
.signWith(SignatureAlgorithm.HS512, secret);
return builder.compact();
}
}
```
其中,JwtTokenUtil类中的generateToken方法用于生成JWT Token,getUsernameFromToken和getExpirationDateFromToken方法用于解析JWT Token中的用户名和过期时间,isTokenExpired方法用于判断JWT Token是否已经过期,refreshToken方法用于刷新JWT Token,validateToken方法用于验证JWT Token是否有效,getClaimsFromToken方法用于从JWT Token中获取Claims。
然后在Spring Security的配置类中添加JwtTokenFilter来实现JWT的过滤和验证:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private JwtTokenFilter jwtTokenFilter;
@Autowired
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtTokenFilter, UsernamePasswordAuthenticationFilter.class);
}
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
```
其中,SecurityConfig类中的configure方法用于配置Spring Security的策略,addFilterBefore方法用于添加JwtTokenFilter,authenticationManagerBean方法用于获取AuthenticationManager。
最后,在登录接口中,使用JwtTokenUtil生成JWT Token并返回给前端:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AuthController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
private UserDetailsService userDetailsService;
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody AuthRequest authRequest) throws Exception {
try {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(authRequest.getUsername(), authRequest.getPassword())
);
UserDetails userDetails = userDetailsService.loadUserByUsername(authRequest.getUsername());
String token = jwtTokenUtil.generateToken(userDetails);
return ResponseEntity.ok(new AuthResponse(token));
} catch (Exception e) {
throw new Exception("Incorrect username or password", e);
}
}
}
```
其中,AuthController类中的login方法用于处理登录请求,通过authenticationManager.authenticate方法验证用户名和密码,然后使用JwtTokenUtil生成JWT Token并返回给前端。
阅读全文