我有以下結構彈簧引導REST服務加載從application.properties值:不能在春季啓動服務
├── src
│ ├── main
│ │ ├── java
│ │ │ ├── daos
│ │ │ ├── db
│ │ │ │ └── DBConnector.java
│ │ │ ├── serviceComponents
│ │ │ │ └── serviceResources
│ │ │ │ ├── Application.java
│ │ │ │ ├── UserController.java
│ │ │ │ └── UserDAO.java
│ │ │ └── serviceRepresentations
│ │ │ └── User.java
│ │ └── resources
│ │ └── application.properties
有關這個問題的主要文件是:
Application.java
:
package serviceComponents.serviceResources;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication(exclude = {ErrorMvcAutoConfiguration.class})
@ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
DBConnector.java
:
package db;
import java.sql.Connection;
import java.sql.SQLException;
import oracle.jdbc.pool.OracleDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
public class DBConnector {
@Value("${current.app.url}")
String dbUrl;
@Value("${current.app.sid}")
String dbSid;
@Value("${current.app.port}")
String dbPort;
@Value("${current.app.user}")
String dbUser;
@Value("${current.app.password}")
String dbPassword;
String jdbcUrl = String.format("jdbc:oracle:thin:@%s:%s:%s", dbUrl, dbPort, dbSid);
Connection conn;
int count = 0;
public DBConnector() {}
@PostConstruct
private void init() {
try {
Class.forName("oracle.jdbc.OracleDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
OracleDataSource ds = null;
try {
ds = new OracleDataSource();
} catch (SQLException e) {
e.printStackTrace();
}
ds.setURL(jdbcUrl);
try {
conn = ds.getConnection(dbUser, dbPassword);
} catch (SQLException e) {
e.printStackTrace();
}
}
public Connection getDBConnection() throws SQLException {
if (count == 0) {
init();
count++;
}
return conn;
}
}
而且properties
文件:
server.port = 8089
test.app.url = 127.0.0.1
test.app.sid = XE
test.app.port = 1521
test.app.user = foouser
test.app.password = barbazpass
current.app.url = test.app.url
current.app.sid = test.app.sid
current.app.port = test.app.port
current.app.user = test.app.user
current.app.password = test.app.password
而且有從控制器相關的代碼:
@RestController
@RequestMapping("/v1/user/")
public class UserController {
DBConnector dbConnector = new DBConnector();
UserDAO userDAO = new UserDAO(dbConnector);
然而,當我運行應用程序,從DBConnector.java
與@Value
註釋的字段沒有使用配置文件中的預期值填充。我知道spring引導會檢測到application.properties
作爲項目的默認配置文件。我究竟做錯了什麼?
你是如何獲得'DBConnector'的實例?鑑於它的包是'db',並且你正在'serviceComponents.serviceResources'中進行組件掃描,Spring根本就不知道它。 –
我已經用控制器的代碼片段更新了這個問題。基本上我在控制器中創建了一個'DBConnector'的實例。 – cristid9