面试题答案
一键面试性能优化
- 缓存设计(使用Redis)
- 引入依赖:在
pom.xml
中添加Redis依赖。
- 引入依赖:在
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- **配置Redis**:在`application.properties`中配置Redis连接信息。
spring.redis.host=localhost
spring.redis.port=6379
- **使用缓存**:在Service层方法上使用`@Cacheable`注解。例如:
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Cacheable("users")
public List<User> getAllUsers() {
// 数据库查询逻辑
}
}
- 优化数据库查询
- 使用索引:对频繁查询的字段添加索引。例如,在MySQL中:
CREATE INDEX idx_username ON users(username);
- **分页查询**:避免一次性加载大量数据。在Spring Data JPA中:
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
Page<User> findAll(Pageable pageable);
}
// 使用
Pageable pageable = PageRequest.of(0, 10);
Page<User> users = userRepository.findAll(pageable);
安全加固
- 防止SQL注入
- 使用参数化查询:在Spring JDBC中,使用
NamedParameterJdbcTemplate
。
- 使用参数化查询:在Spring JDBC中,使用
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class UserRepository {
@Autowired
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
public User getUserById(Long id) {
String sql = "SELECT * FROM users WHERE id = :id";
SqlParameterSource namedParameters = new MapSqlParameterSource("id", id);
return namedParameterJdbcTemplate.queryForObject(sql, namedParameters, new UserRowMapper());
}
}
- 防止XSS攻击
- 对输出进行编码:在Spring MVC中,可以使用
HttpMessageConverter
对响应数据进行编码。例如,在配置类中:
- 对输出进行编码:在Spring MVC中,可以使用
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.nio.charset.StandardCharsets;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Bean
public StringHttpMessageConverter stringHttpMessageConverter() {
StringHttpMessageConverter converter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
converter.setWriteAcceptCharset(false);
return converter;
}
}
- Spring Security身份认证和授权高级配置
- 引入依赖:在
pom.xml
中添加Spring Security依赖。
- 引入依赖:在
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
- **配置类**:创建一个配置类继承`WebSecurityConfigurerAdapter`。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Bean
@Override
public UserDetailsService userDetailsService() {
UserDetails user =
User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
UserDetails admin =
User.withDefaultPasswordEncoder()
.username("admin")
.password("admin")
.roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(user, admin);
}
}
整体思路是先从性能角度优化缓存和数据库查询,减少响应时间和资源消耗;再从安全角度防止常见Web攻击,并利用Spring Security进行身份认证和授权,确保API的安全性。关键配置代码如上述所示,根据实际业务场景可能需要进一步调整。