0

在我的 Spring Boot 应用程序中,我使用调用存储过程的方法实现了以下类。

@Component
@ConfigurationProperties(prefix = "spring")
public class FmTrfUtil {
    static int returnVal;
    @Value("${spring.datasource.url}")
    static String url;

    public static int insertFmTrfs(List<String> trfs, String source) {
        System.out.println(url);
        EntityManager em = Persistence.createEntityManagerFactory("RIStore_FM").createEntityManager();
        Session session = em.unwrap( Session.class );
        final String[] trfArray = trfs.toArray(new String[trfs.size()]);
        final String src = source;

        session.doWork( new Work(){
            public void execute(Connection conn) throws SQLException {
                CallableStatement stmt = null;               
                OracleConnection oraCon = conn.unwrap(OracleConnection.class);
                Array array = oraCon.createARRAY("VARCHAR2_TAB_T", trfArray);
                stmt = conn.prepareCall("{? = call FM_TRF_UTIL.process_fm_trf(?,?)}");
                stmt.registerOutParameter(1, Types.INTEGER);
                stmt.setArray(2, array);
                stmt.setString(3, src);
                stmt.execute();
                returnVal = stmt.getInt(1);
            }
        });
        return returnVal;
    }
}

由于调用存储过程需要数据库连接,我需要从 application.properties 中加载这些对应的属性值:

spring.profiles.active=dev
spring.datasource.url=jdbc:oracle:thin:@ldap://xxx:389/risdev3, cn=OracleContext,dc=x,dc=net
spring.datasource.username=owner
spring.datasource.password=owner987

基于以下关于类似问题的文章,Spring boot - Application.properties 中的自定义变量在您自己的类中使用 Spring-Boot 配置属性Spring Boot @ConfigurationProperties 示例,我为我的类添加了这个注释@ConfigurationProperties(prefix = "spring")(数据库连接的属性都有“弹簧”作为前缀)。但是,当我使用如下测试类运行它时,出现错误“应用程序必须提供 JDBC 连接”,这意味着 application.properties 中的属性没有被拾取。

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = RistoreWebApplication.class, initializers = ConfigFileApplicationContextInitializer.class)
public class FmTrfUtilTest {
    @Test
    public void test() {
        List<String> trfs = new ArrayList<String>();
        trfs.add("TRF000001");
        trfs.add("TRF000002");
        int ret = FmTrfUtil.insertFmTrfs(trfs, "SARC");
        assertTrue(ret > 0);
    }
}

为了@ConfigurationProperties工作,我也添加了 Maven 依赖spring-boot-configuration-processor项。为什么它仍然不起作用?我错过了什么?

4

1 回答 1

1

这里有几件事是错误的:

  • @Value不适用于静态字段
  • @ConfigurationProperties用于从 Java 对象绑定字段application.properties或将字段绑定application.yml到 Java 对象。查看@ConfigurationPropertiesSpring Boot 本身的任何带注释的类,以轻松理解它应该如何使用。
  • 你不应该使用你自己@ConfigurationProperties的前缀spring,因为它已经被 Spring Boot 本身使用了
  • spring-boot-configuration-processor仅用于在 IDE 中更好地完成代码。你不需要这个。

如果您想利用 Spring Boot 配置属性进行数据库连接,而不是EntityManager像您这样创建:

EntityManager em = Persistence.createEntityManagerFactory("RIStore_FM").createEntityManager();

假设您的依赖项列表中有 Spring Data JPA Starter,您应该只注入它。

我看到你使用了很多static方法和领域。这不适用于Spring。改用依赖注入并自动装配你需要的东西。

于 2016-11-04T21:02:14.430 回答