Reputation: 596
In my application.properties i have some spring.datasource
fields
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE
spring.datasource.username=talon
spring.datasource.password=talon
These should be retrieved from a @Configuration
annotated class
@Configuration
public class Db {
@NotNull
private String username;
@NotNull
private String password;
@NotNull
private String url;
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setUrl(String url) {
this.url = url;
}
public Db() {
OracleDataSource dataSource = null;
try {
dataSource = new OracleDataSource();
dataSource.setUser(username);
dataSource.setPassword(password);
dataSource.setURL(url);
dataSource.setImplicitCachingEnabled(true);
dataSource.setFastConnectionFailoverEnabled(true);
Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from BOOK");
rs.next();
System.out.println(rs.getString(2));
} catch (SQLException e) {
e.printStackTrace();
}
}
}
But I'm unable to retrieve the username
password
and url
from there, should I add another annotation somewhere or what am I doing
Like this I have the error: java.sql.SQLException: Invalid Oracle URL specified: OracleDataSource.makeURL
If I set the proper url with dataSource.setURL("jdbc:oracle:thin:@localhost:1521:XE");
it can't read the username
and password
since they are null and I have java.sql.SQLException: ORA-01017: invalid username/password; logon denied
Upvotes: 0
Views: 2164
Reputation: 8606
You have two issues:
You need to use another annotation in order for your fields to be populated. So annotate the class with @ConfigurationProperties("spring.datasource")
You cannot initialize your OracleDataSource
directly in your constructor (i.e. Db()
) because the properties (your username/password/url fields) are not populated during the call of the constructor, so one thing that you can do is create another method and annotate that with @PostContruct
in order for your dataSource
to be correctly created.
An example:
@PostConstruct
private void init() {
// your data source initialization
}
One advice would be to change the way to initialize your dataSource and instead of trying to create it inside your constructor, you can rather create a new method which you can annotate with @Bean
and make it return your dataSource and you can use it later using @Autowired
.
Upvotes: 1