小编Sam*_*amo的帖子

如何声明父应用程序上下文

我发现自己在applicationContext.xml和applicationContext-test.xml中使用了两个相同的bean.我希望我的测试上下文能够从我的应用程序上下文继承,以避免重复自己.

我已经看到很多材料表明你可以从该上下文声明父应用程序上下文和引用bean,但我找不到一个有用的例子.有人可以帮忙吗?

更新 作为一些背景信息,我的正常应用程序上下文正在web.xml中加载:

<context-param>
    <description>Application Contexts for Spring</description>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> 
Run Code Online (Sandbox Code Playgroud)

我的测试应用程序上下文在我的单元测试中加载:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext-test.xml")
Run Code Online (Sandbox Code Playgroud)

所以,假设我在常规环境中有一个bean:

<bean name="someBean" class="com.foo.MyClass" />
Run Code Online (Sandbox Code Playgroud)

然后,在我的测试应用程序上下文中,我想引用这个bean.我该怎么做?

更新

根据skaffman的建议,我已将bean移动到SharedBeans.xml文件中并将其导入到我的applicationContext.xml中.但是,这会导致SAXParser异常:

org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from URL location [classpath:SharedBeans.xml]
Offending resource: ServletContext resource [/WEB-INF/classes/applicationContext.xml]; nested exception is org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 1 in XML document from class path resource [SharedBeans.xml] is invalid; nested exception is org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'bean'.
    at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)
Run Code Online (Sandbox Code Playgroud)

我无法确定我做错了什么.bean在我的上下文文件中工作正常,我所做的就是剪切并粘贴到新文件中.以下是SharedBeans.xml的完整内容:

<bean name="properties" class="com.foo.Properties">
    <constructor-arg><value>${module.name}</value></constructor-arg> …
Run Code Online (Sandbox Code Playgroud)

spring

8
推荐指数
1
解决办法
1万
查看次数

支持Spring-MVC控制器中的多种内容类型

Rails控制器使得支持多种内容类型变得非常容易.

respond_to do |format|
  format.js { render :json => @obj }
  format.xml
  format.html
end
Run Code Online (Sandbox Code Playgroud)

美丽.在一个控制器动作中,我可以轻松地响应多种内容类型,并且具有足够的灵活性,可以呈现我想呈现的内容,无论是模板,对象的序列化形式等.

我可以在Spring-MVC中做类似的事情吗?在Spring中支持多种内容类型的标准是什么?我见过涉及视图解析器的解决方案,但这看起来很难管理,特别是如果我想支持除xhtml和xml之外的JSON.

任何建议都表示赞赏,但更简单,更优雅的解决方案将更受欢迎;)

编辑

如果我断言查看解析器很难管理,请随时纠正我并提供一个示例.最好是可以返回xml,xhtml和JSON的.

java model-view-controller content-type ruby-on-rails spring-mvc

8
推荐指数
1
解决办法
6919
查看次数

如何从模板访问对象的属性?

根据http://handlebarsjs.com/expressions.html,我应该可以这样做:

<h1>{{article.title}}</h1>
Run Code Online (Sandbox Code Playgroud)

但我似乎无法让它在流星中发挥作用.这是我的模板:

<template name="content">
  {{#if item}}
    <p>{{item.name}}</p>
  {{/if}}
</template>
Run Code Online (Sandbox Code Playgroud)

这是返回项目的JavaScript:

  Template.content.item = function() {
    return Items.findOne({ _id: Session.get("list_id") });
  };
Run Code Online (Sandbox Code Playgroud)

是的,该项确实有一个名为name:-) 的属性

当我这样做时,我发现Firebug中有一个错误 ret is undefined

这可以追溯到evaluate.js:

for (var i = 1; i < id.length; i++)
  // XXX error (and/or unknown key) handling
  ret = ret[id[i]];
return ret; 
Run Code Online (Sandbox Code Playgroud)

在错误发生时,ret引用该window对象.那是怎么回事?

javascript meteor spacebars

8
推荐指数
1
解决办法
1万
查看次数

为什么常规应用程序上下文无法加载我的属性文件?

我正在尝试在我的应用程序中使用PropertyPlaceholderConfigurer.我的applicationContext-test.xml很好地加载了我的属性文件,但是我的applicationContext.xml引发了异常.在这两种情况下,我正在加载我的属性文件,如下所示:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">    
    <property name="location">
        <value>localdevelopment_Company.properties</value>
    </property>
</bean>
Run Code Online (Sandbox Code Playgroud)

当我运行我的测试时,它没有抱怨,但是当我启动我的服务器时,我得到了这个异常:

SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanInitializationException: Could not load properties; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/localdevelopment_Company.properties]
    at org.springframework.beans.factory.config.PropertyResourceConfigurer.postProcessBeanFactory(PropertyResourceConfigurer.java:78)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:663)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:638)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:407)
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4135)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4630)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:785)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:445)
    at org.apache.catalina.core.StandardService.start(StandardService.java:519)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:581)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at …
Run Code Online (Sandbox Code Playgroud)

java spring properties spring-mvc

7
推荐指数
1
解决办法
7868
查看次数

Rails:为什么在rake任务中调用to_a字符串无效?

我正在尝试为数据库迁移解密一堆密码.我有一些旧的Rails代码(实际上是一个Runner脚本),可以很好地解密它们.但是将相同的代码放入Rake任务会导致任务失败,并且...未定义的方法`to_a'表示"secretkey":String ...

为什么在Rake任务中调用字符串上的to_a无效,但在Runner脚本中完全有效?

require 'openssl'

KEY = 'secretkey'

  namespace :import do
  task :users => :environment do
      def decrypt_password(pw)

          cipher = OpenSSL::Cipher::Cipher.new('bf-ecb')
          cipher.decrypt
          cipher.key = KEY.to_a.pack('H*')    <<--------- FAILS RIGHT HERE on to_a

          data = data.to_a.pack('H*')
          data = cipher.update(data)
          data << cipher.final
          unpad(data)

      end
   end

   ... other methods
end
Run Code Online (Sandbox Code Playgroud)

(Rails 3.0.0,Ruby 1.9.2)

ruby string rake ruby-on-rails

7
推荐指数
3
解决办法
8138
查看次数

在Play模板中混合使用JavaScript和Scala

我不确定这是怎么做的.我可以硬编码我正在尝试使用的路线,但我想以正确的方式做到这一点.

我有一个需要在更改时加载新页面的下拉列表.这基本上是我试图这样做的(我尝试了一些变体):

@getRoute(value: String) = @{
    routes.Accounts.transactions(Long.valueOf(value))
}

    <script type="text/javascript">
      $(function() {

        $("select[name='product']").change(function() {

          location.href = @getRoute($(this).val());
        }).focus();

        $('a.view.summary').attr('href', "@routes.Accounts.index()" + "?selectedAccountKey=" + $('select[name=product]').val());
      });
    </script>
Run Code Online (Sandbox Code Playgroud)

这会产生identifier expected but 'val' found异常.我也尝试用引号括起来,但这导致了[NumberFormatException: For input string: "$(this).val()"]

那么我如何将JavaScript中的值插入Scala函数呢?

编辑

这是我的解决方案,受到公认答案的启发.此下拉列表在一个标记中定义,该标记用于不同组件的重用,并且每个组件的基本URL都不同.实现此目的的方法是将基于帐户密钥生成URL的函数传递到下拉列表中:

@(accountList: List[models.MemberAccount],
  selectedAccountKey: Long,
  urlGenerator: (Long) => Html
)

<select name="product">
  @for(account <- accountList) {
    @if(account.accountKey == selectedAccountKey) {
      <option selected="selected" value="@urlGenerator(account.accountKey)">@account.description (@account.startDate)</option>
    } else {
      <option value="@urlGenerator(account.accountKey)">@account.description (@account.startDate)</option>
    }
  }
</select>

<script type="text/javascript">
$(function() {
    $('select[name=product]').change(function() {
        location.href …
Run Code Online (Sandbox Code Playgroud)

javascript scala playframework

6
推荐指数
1
解决办法
7169
查看次数

QueryStringBindable用于自定义枚举

我已经定义了一个Format实现的枚举类型QueryStringBindable.我想我已经正确实现了它,但在我的路由文件中,我不能将我的类型指定为路由参数,因为编译器找不到它,我不知道如何将它导入路由文件.

这是枚举:

package web;

import java.util.Map;

import play.libs.F;
import play.mvc.QueryStringBindable;

public enum Format implements QueryStringBindable<Format> {
    Html,
    Pdf,
    Csv;

    private Format value;

    @Override
    public F.Option<Format> bind(String key, Map<String, String[]> data) {
        String[] vs = data.get(key);
        if (vs != null && vs.length > 0) {
            String v = vs[0];
            value = Enum.valueOf(Format.class, v);
            return F.Option.Some(value);
        }
        return F.Option.None();
    }

    @Override
    public String unbind(String key) {
        return key + "=" + value;
    }

    @Override
    public String javascriptUnbind() { …
Run Code Online (Sandbox Code Playgroud)

java enums query-string playframework

6
推荐指数
2
解决办法
1190
查看次数

将此XML反序列化为对象的最佳方法

在其他示例中,我看到它与我的相似,有一个根节点,然后是一个数组节点,然后是一堆数组项.我的问题是,我的根节点我的数组节点,所以我看到的示例似乎对我不起作用,我无法更改XML模式.这是XML:

<articles>  
    <article>
      <guid>7f6da9df-1a91-4e20-8b66-07ac7548dc47</guid>
      <order>1</order>
      <type>deal_abstract</type>
      <textType></textType>
      <id></id>
      <title>Abu Dhabi's IPIC Eyes Bond Sale After Cepsa Buy</title>
      <summary>Abu Dhabi's IPIC has appointed banks for a potential sterling and euro-denominated bond issue, a document showed on Wednesday, after the firm acquired Spain's Cepsa in a $5 billion deal earlier this month...</summary>
      <readmore></readmore>
      <fileName></fileName>
      <articleDate>02/24/2011 00:00:00 AM</articleDate>
      <articleDateType></articleDateType>
    </article>

    <article>
      <guid>1c3e57a0-c471-425a-87dd-051e69ecb7c5</guid>
      <order>2</order>
      <type>deal_abstract</type>
      <textType></textType>
      <id></id>
      <title>Big Law Abuzz Over New China Security Review</title>
      <summary>China’s newly established foreign investment M&amp;A review …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc xml-deserialization

5
推荐指数
2
解决办法
8073
查看次数

ScenarioContext.Current线程安全吗?

我觉得它不是.我有三个集成测试,当单独运行时会成功,但是当并行运行时,我得到了System.ArgumentException: An item with the same key has already been added.

我当然希望ScenarioContext.Current总能提到正确的情况,但似乎它变得混乱了.有没有人成功地为这个类增加了线程安全性?或者我是否应该使用另一种方法在步骤文件之间共享值?

c# bdd concurrency specflow

5
推荐指数
1
解决办法
1911
查看次数

如何在动态路由上设置http-proxy-middleware?

我正在尝试代理一些资产路由,其中​​路径的动态部分来自配置文件。我使用该request库进行了此工作,但我无法完全使其与http-proxy-middleware.

这是我使用该库时有效的代码request

  const assets = express.Router();
  app.use(`/${p.name}/assets`, assets);
  assets.get('*', async (req, res) => {
    return request(`${p.address}/${p.version}/assets${req.path}`).pipe(res);
  });
Run Code Online (Sandbox Code Playgroud)

我尝试了一些不同的变体http-proxy-middleware,但这些都不起作用。示例1:

  app.use(
    `/${p.name}/assets`,
    httpProxy({
      target: `${p.address}`,
      changeOrigin: true,
      pathRewrite: {
        [`^${p.name}`]: `${p.version}`,
      },
    })
  );
Run Code Online (Sandbox Code Playgroud)

示例2:

  app.use(
    `/${p.name}/assets`,
    httpProxy({
      target: `${p.address}`,
      changeOrigin: true,
      pathRewrite: function(path) {
        return path.replace(p.name, p.version);
      }
    })
  );
Run Code Online (Sandbox Code Playgroud)

我还尝试使用/${p.name}/assets/**作为 的第一个参数app.use,并且还尝试将 a 添加到对象/assets中的键和值的末尾pathRewrite。结果总是一样的:我得到浏览器请求的资源的 302。

我什至尝试在记录到控制台的调用之前添加一个中间件函数httpProxy,以便我知道我的请求到达了正确的路线:

  app.use(
    `/${p.name}/assets`,
    (req, _res, …
Run Code Online (Sandbox Code Playgroud)

node.js express http-proxy-middleware

5
推荐指数
1
解决办法
4250
查看次数