Spring Boot 经典面试题(三)

发布于:2024-04-12 ⋅ 阅读:(162) ⋅ 点赞:(0)

1. Spring Boot如何配置多数据源?

在 Spring Boot 中配置多个数据源意味着你的应用将能够连接到多个数据库。这在许多场景中都非常有用,比如当你的应用需要同时访问关系型数据库和 NoSQL 数据库,或者需要访问多个关系型数据库时。要实现这一点,你需要定义额外的数据源、EntityManager、事务管理器等,并确保 Spring Boot 能够正确区分它们。下面是通过配置多个数据源的基本步骤,以及如何在 Spring Boot 应用中使用它们:

步骤 1: 添加依赖

首先,确保你的 pom.xmlbuild.gradle 文件中包含了对 JDBC 和 JPA (如果你使用 JPA) 的支持:

<!-- 对于 Maven 用户 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>
<!-- 添加其他数据库的依赖 -->

对于 Gradle,添加类似的依赖。

步骤 2: 配置数据源

application.propertiesapplication.yml 文件中,为每个数据源配置属性。例如:

# 主数据源
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver

# 第二数据源
app.datasource.secondary.url=jdbc:mysql://localhost:3306/second_db
app.datasource.secondary.username=root
app.datasource.secondary.password=root
app.datasource.secondary.driver-class-name=com.mysql.cj.jdbc.Driver

步骤 3: 配置数据源 Bean

在你的配置类中,为每个数据源定义一个 DataSourceEntityManagerFactoryTransactionManager。你需要使用 @Primary 注解标记其中一个数据源作为主数据源。

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
  basePackages = "com.example.primary",
  entityManagerFactoryRef = "primaryEntityManagerFactory",
  transactionManagerRef = "primaryTransactionManager"
)
public class PrimaryDataSourceConfig {

    @Primary
    @Bean(name = "primaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "primaryEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean primaryEntityManagerFactory(
            EntityManagerFactoryBuilder builder, @Qualifier("primaryDataSource") DataSource dataSource) {
        return builder
                .dataSource(dataSource)
                .packages("com.example.primary.model")
                .persistenceUnit("primary")
                .build();
    }

    @Primary
    @Bean(name = "primaryTransactionManager")
    public PlatformTransactionManager primaryTransactionManager(
            @Qualifier("primaryEntityManagerFactory") EntityManagerFactory primaryEntityManagerFactory) {
        return new JpaTransactionManager(primaryEntityManagerFactory);
    }
}

// 为第二数据源创建一个相似的配置类,但不要包含 @Primary 注解,并更改相关的方法名和属性名。

步骤 4: 使用数据源

在你的服务或数据访问对象 (DAO) 中,使用 @Autowired 注解注入对应的 EntityManagerJdbcTemplate,并确保它们指向正确的数据源。

注意事项

  • 确保正确区分数据源:特别是在定义 JPA 仓库接口时,确保它们指向正确的数据源。
  • 事务管理:如果你的操作涉及跨多个数据源的事务,可能需要更复杂的事务管理策略,如使用 JTA 或分布式事务解决方案。
  • 性能考量:管理多个数据库连接可能会对应用性能产生影响,特别是在高负载情况下。

通过遵循这些步骤,你可以在 Spring Boot 应用中成功配置和使用多个数据源。

2.Spring Boot中如何实现AOP?

在Spring Boot中实现AOP(面向切面编程)可以通过以下步骤:

  1. 添加依赖:首先,在pom.xml文件中添加Spring Boot AOP的依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
  1. 创建切面类:创建一个Java类作为切面。这个类包含各种通知(Before、After、Around等),并且通过切入点表达式定义了哪些方法需要被通知。
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class MyAspect {
    
    @Before("execution(* com.example.demo.service.*.*(..))")
    public void beforeAdvice() {
        System.out.println("Before method execution");
    }
}
  1. 配置切面:确保在Spring Boot应用程序的配置类中启用了AOP。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@SpringBootApplication
@EnableAspectJAutoProxy
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
  1. 测试:编写一个测试类来验证AOP是否按预期工作。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class MyRunner implements CommandLineRunner {

    @Autowired
    private MyService myService;

    @Override
    public void run(String... args) throws Exception {
        myService.doSomething();
    }
}
import org.springframework.stereotype.Service;

@Service
public class MyService {

    public void doSomething() {
        System.out.println("Doing something...");
    }
}

运行应用程序,输出应该包含“AOP通知”和“正在执行”的消息,这表明切面已经成功地应用于目标方法。

这就是在Spring Boot中实现AOP的基本步骤。你可以根据需要添加更多的通知类型和切入点表达式来实现更复杂的切面逻辑。

3.Spring Boot的事务管理是如何实现的?

在Spring Boot中,事务管理是通过Spring框架的事务管理模块来实现的,通常使用@Transactional注解来标记需要事务管理的方法或类。

下面是Spring Boot中实现事务管理的基本步骤:

  1. 添加依赖:首先,在pom.xml文件中添加Spring Boot的事务管理依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
  1. 配置数据源:确保应用程序配置了数据库连接信息,通常在application.propertiesapplication.yml文件中配置数据源相关属性。
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mydatabase
    username: root
    password: password
    driver-class-name: com.mysql.cj.jdbc.Driver
  1. 标记事务:在需要进行事务管理的方法上添加@Transactional注解。
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class MyService {

    @Autowired
    private MyRepository myRepository;

    @Transactional
    public void performTransaction() {
        // 业务逻辑代码
        myRepository.save(entity);
    }
}
  1. 配置事务管理器:Spring Boot会自动配置事务管理器,但是如果需要自定义事务管理器,则需要在配置类中进行配置。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.persistence.EntityManagerFactory;

@Configuration
public class TransactionConfig {

    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }
}

这就是在Spring Boot中实现事务管理的基本步骤。使用@Transactional注解标记需要进行事务管理的方法后,Spring会在方法执行时自动开启事务,并在方法执行完毕后根据执行结果进行提交或回滚事务。


网站公告

今日签到

点亮在社区的每一天
去签到