Spring Boot 2是一个开源的Java框架,用于创建生产级的、基于Spring的应用程序。它可以快速创建独立的、生产级的、基于Spring的应用程序。
在Java面试中,Spring Boot 2的中间件可能会涉及到诸如Spring MVC、Spring Security、Spring Data、Spring Batch等。以下是一些常见的Spring Boot 2中间件的使用示例:
- Spring MVC:Spring MVC是构建Web应用程序的核心框架。以下是一个简单的Spring MVC控制器示例:
@RestController
public class HelloWorldController {
@RequestMapping("/hello")
public String index() {
return "Hello, Spring Boot 2!";
}
}
- Spring Security:Spring Security是一个能够为基于Spring的应用程序提供安全保护的框架。以下是一个简单的Spring Security配置示例:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}
}
- Spring Data:Spring Data是一个用于简化数据库访问的框架。以下是一个简单的Spring Data JPA示例:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// getters and setters
}
public interface UserRepository extends JpaRepository<User, Long> {
}
- Spring Batch:Spring Batch是一个用于处理批量操作的框架。以下是一个简单的Spring Batch作业示例:
@Configuration
@EnableBatchProcessing
public class BatchConfig {
@Autowired
public JobBuilderFactory jobBuilderFactory;
@Autowired
public StepBuilderFactory stepBuilderFactory;
@Bean
public Job importUserJob(Step step) {
return jobBuilderFactory.get("importUserJob")
.start(step)
.build();
}
@Bean
public Step step() {
return stepBuilderFactory.get("step")
.<User, User>chunk(10)
.reader(reader())
.writer(writer())
.build();
}
@Bean
public JdbcPagingItemReader<User> reader() {
JdbcPagingItemReader<User> reader = new JdbcPagingItemReader<>();
reader.setDataSource(dataSource);
reader.setFetchSize(100);
reader.setQueryProvider(new MySqlPagingQueryProvider());
reader.setRowMapper(new BeanPropertyRowMapper<>(User.class));
return reader;
}