You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Apache Camel 2升3.14:Main.setApplicationContextUri()方法去向及配置替代

Apache Camel 3.14.6升级与注解化配置指引

1. Main.setApplicationContextUri方法的替代方案

Camel 3.x移除了Main.setApplicationContextUri()方法,可通过手动创建Spring上下文并绑定到Camel Main实例实现替代:

import org.apache.camel.spring.Main;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class CamelAppMain {
    public static void main(String[] args) throws Exception {
        Main main = new Main();
        // 加载现有Spring配置文件
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("app-context.xml");
        main.setApplicationContext(context);
        main.run(args);
    }
}

若已完全转向注解配置,可直接加载配置类:

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

// ...
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(CamelConfig.class);
main.setApplicationContext(context);

2. 用Bean和注解替代XML配置的步骤

2.1 创建核心配置类

替代原camel-context.xml中的Camel上下文、属性占位符与组件配置:

import org.apache.camel.component.sql.SqlComponent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DataSource;

@Configuration
@PropertySource("classpath:lib/queries.properties") // 替代XML中的propertyPlaceholder
@ComponentScan(basePackages = "com.blah.listener") // 替代XML中的路由扫描配置
public class CamelConfig {

    // 注册SQL组件
    @Bean
    public SqlComponent sqlComponent(DataSource dataSource) {
        SqlComponent component = new SqlComponent();
        component.setDataSource(dataSource);
        return component;
    }

    // 注册原XML中的自定义Bean
    @Bean
    public com.foo.OurThing bean1() {
        return new com.foo.OurThing();
    }

    @Bean
    public com.bar.OtherThing bean2() {
        return new com.bar.OtherThing();
    }
}

2.2 路由类注解化改造

原com.blah.listener下的路由类需添加Spring与Camel注解:

import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;

@Component
public class SampleRoute extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        // 示例路由逻辑,可替换为你的业务代码
        from("direct:start")
          .to("sql:{{select.query}}");
    }
}

3. app-context.xml中camel-context.xml引用的处理

  • 若完全迁移到注解配置:直接移除app-context.xml中对camel-context.xml的引用,改为通过<context:component-scan base-package="你的配置类所在包"/>或<bean class="com.your.config.CamelConfig"/>引入注解配置类。
  • 若暂时保留部分XML配置:可将camel-context.xml的内容合并到app-context.xml中,或保持引用但确保XML语法兼容Camel 3.x的Spring Schema(原XML中的命名空间已适配3.x,无需修改schemaLocation)。

内容的提问来源于stack exchange,提问作者user26270

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 18:50:25