我想将Spring应用程序(大部分)转换为Spring Boot应用程序。在应用程序中,我有一个HTTP基本过滤器,用于收集用户名和密码,然后将其作为DataSource实现中的变量传递。覆盖默认数据源getConnection()
在此DataSource的getConnection()方法是这样:
@Override\n public Connection getConnection() throws SQLException {
Statement stmt = null;
try {
ConnectionWrapper connection = this.authenticatedConnection.get();
if (connection == null) {
connection = new ConnectionWrapper(this.dataSource.getConnection());
StringBuilder command;
// The CONNECT command allows indicating a user name, a password
// and a database to initiate a
// new session in the server with a new profile.
command = new StringBuilder("CONNECT USER ").append(this.parameters.get().get(USER_NAME)).append(" PASSWORD ")
.append("'").append(this.parameters.get().get(PASSWORD_NAME)).append("'").append(" DATABASE ")
.append(this.parameters.get().get(DATA_BASE_NAME));
this.authenticatedConnection.set(connection);
stmt = connection.createStatement();
stmt.execute(command.toString());
}
return connection;
} catch (final SQLException e) {...`
(含\ n作为新行由于StackOverflow的格式问题)
在春天,我能够实现@ Autowired Private DataSource数据源没有问题。在Spring Boot中,据我所知,对象需要是使用@Autowired的Bean,但是当我在此实现的DataSource之前添加@Bean时,我会得到“注释@Bean不允许用于此位置”
如何能我得到它,以便我可以做一个dataSource.getConnection();并从主数据源获取连接,或者能够覆盖主数据源的方法?
我看到它的方式,也有优先顺序这里列出4级可能的解决方案:
- 创建一个数据源,实际上是覆盖spring.datasource”的方法。
- 获取此实现“Bean化”,所以我可以@Autowired数据源再次。
- 我想可以跳过@Autowired和简单地设定this.dataSource = [未知参照spring.datasource在application.properties定义]
- 创建另一个DataSource类ProgrammedDataSource与spring.datasource属性来配置,然后将其设置as this.dataSource = new ProgrammedDataSource();
但我在实施任何这些解决方案的尝试都产生了这个问题。
您是否理解可用于指示类是Spring bean的各种构造型注释(这是一个提示)? –
感谢您提供更多Google搜索。 – MBudnick
我已经将其缩小到@Repository注释。 我现在正在处理它,并会在我得到它时提供答案。 (如果没有其他人有可接受的回应。) – MBudnick