首页 文章

依赖注入数据源和jdbctemplate?

提问于
浏览
1

我对webapp开发一般都是新手,特别是Spring框架 . 我正在关注这个Spring JDBC Transactions tutorial但是我不想仅从一个类访问数据库服务,而是希望从多个类中访问它 .

在本教程中,服务定义如下

public class BookingService {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Transactional
    public void book(String... persons) {
        for (String person : persons) {
            System.out.println("Booking " + person + " in a seat...");
            jdbcTemplate.update("insert into BOOKINGS(FIRST_NAME) values (?)", person);
        }
    };

    public List<String> findAllBookings() {
        return jdbcTemplate.query("select FIRST_NAME from BOOKINGS", new RowMapper<String>()     
            @Override
            public String mapRow(ResultSet rs, int rowNum) throws SQLException {
                return rs.getString("FIRST_NAME");
            }
        });
    }

}

这些是 beans 类

@Configuration
@EnableTransactionManagement
@EnableAutoConfiguration
public class Application {

@Bean
BookingService bookingService() {
    return new BookingService();
}

@Bean
DataSource dataSource() {
    return new SimpleDriverDataSource() {{
        setDriverClass(org.h2.Driver.class);
        setUsername("sa");
        setUrl("jdbc:h2:mem");
        setPassword("");
    }};
}

@Bean
JdbcTemplate jdbcTemplate(DataSource dataSource) {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    System.out.println("Creating tables");
    jdbcTemplate.execute("drop table BOOKINGS if exists");
    jdbcTemplate.execute("create table BOOKINGS(" +
            "ID serial, FIRST_NAME varchar(5) NOT NULL)");
    return jdbcTemplate;
}

他们仅在Application类中实例化该服务,并在那里完成所有事务

ApplicationContext ctx = SpringApplication.run(Application.class, args);
BookingService bookingService = ctx.getBean(BookingService.class);

//bookingService.doStuff()

在我的测试项目中,我复制了相同的Bean定义,但我在多个类中执行了事务 .

public class foo {
    ApplicationContext ctx = new AnnotationConfigApplicationContext(Application.class);
    BookingService bookingService = ctx.getBean(BookingService.class);
    bookingService.book(...);
    // some other stuff
}

public class bar {
    ApplicationContext ctx = new AnnotationConfigApplicationContext(Application.class);
    BookingService bookingService = ctx.getBean(BookingService.class);
    bookingService.findAllBookings(...);
    // some other stuff
}

似乎当我只在一个类中执行所有事务时(例如,在foo类中预订和查找),它会按预期执行 . 但是当我尝试将它们分成多个类时,它的行为并不像预期的那样 . 如果我在foo中执行这本书,我找不到吧 . 我错过了什么概念?我实例化数据源和jdbctemplate的多个实例,因为我多次实例化该服务 . 但我认为Spring处理注射?由于只有一个物理数据库,因此只有一个数据源和jdbctemplate实例 . 我误解了什么概念?请帮助并指出正确的方向 . 谢谢 .

1 回答

  • -1

    您需要注入依赖项,例如:

    public class Foo {
    
        @Autowired
        private BookingService bookingService;
    
        public doStuff() {
            bookingService.book(...);
            // some other stuff
        }
    }
    

相关问题