标签: spring-3

如何从Constructor访问@Value注释变量?

我想创建一个具有属性文件值的bean.我做了这样的事情:

@Component
public class MainNavs implements Iterable<Nav>{
    @Value("${newshome.navs.names}")
    String[] names;

    @Value("${newshome.navs.ids}")
    String[] ids;

    final private List<Nav> navs = new ArrayList<Nav>();

    public MainNavs() throws Exception {            
        for (int i = 0; i < names.length; i++) {
            navs.add(new Nav(names[i], ids[i]));
        }
    }

    public Iterator<Nav> iterator() {
        Iterator<Nav> n = navs.iterator();
        return n;
    }

    public class Nav {      
        private String name;
        private String id;
        private String imageNumber;

        public Nav(String name, String id, String imageNumber) {
            this.name = name;
            this.id = id;
        }

        //.... …
Run Code Online (Sandbox Code Playgroud)

java spring annotations spring-mvc spring-3

2
推荐指数
1
解决办法
2081
查看次数

Spring 错误 - java.lang.NoSuchMethodError: &gt; org.springframework.beans.factory.annotation.InjectionMetadata.&lt;init&gt;

各位,

我正在尝试运行一个简单的 spring 使用示例@Required.

但是,当我运行主方法类时,我得到以下异常跟踪?

线程“main”中的异常 java.lang.NoSuchMethodError: org.springframework.beans.factory.annotation.InjectionMetadata.(Ljava/lang/Class;Ljava/util/Collection;)V at org.springframework.orm.jpa.support。 PersistenceAnnotationBeanPostProcessor.findPersistenceMetadata(PersistenceAnnotationBeanPostProcessor.java:377)在org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessMergedBeanDefinition(PersistenceAnnotationBeanPostProcessor.java:295)在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.apply MergedBeanDefinitionPostProcessors(AbstractAutowireCapableBeanFactory.java: 750)在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:451)在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:412)在java.security。 AccessController.doPrivileged(本机方法)在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:383)在org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:276)在 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) 在 org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:273) 在 org.springframework.beans.factory .support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:175)在org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:485)在org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java :716)在org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:377)在org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)在org.springframework.context.support.ClassPathXmlApplicationContext .(ClassPathXmlApplicationContext.java:83) 在 com.springexamples.annotation.required.EmployeeTest.main(EmployeeTest.java:19)

类路径中是否缺少任何特定的 jar?

谢谢

java spring annotations jar spring-3

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

Spring 3.1.2 RowMapper参数化

我正在使用Spring 3.1.2开发Web应用程序,并且需要创建自定义行映射器。我创建了一个私有静态最终类,该类实现了RowMapper,但是我收到错误消息“ RowMapper类型不是通用的;不能使用参数对其进行参数化”。

我的lib文件夹中的所有与Spring相关的jar都是3.1.2.RELEASE版本。我一直找不到其他地方的东西。任何想法为什么会发生这种情况?

谢谢。

这是示例代码:

public class OutPatient extends Patient{
     @Pattern(regexp="[0-9]+", message="OPD No. should only contain digits.")
String opdNo;

public String getOpdNo() {
    return opdNo;
}

public void setOpdNo(String opdNo) {
    this.opdNo = opdNo;
}
}
Run Code Online (Sandbox Code Playgroud)

DAO类:

 @Repository("dbHelper")
 public class DBHelperImpl{
private JdbcTemplate jdbcTemplate;
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

@Autowired
public void setDataSource(DataSource dataSource) {
    this.jdbcTemplate = new JdbcTemplate(dataSource);
    this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}

     public List<OutPatient> fetchOutPatients() {
    String sql = "SELECT  OPDNO as opdNo FROM `test`.`out_patient`";

    @SuppressWarnings("unchecked")  //Have to add …
Run Code Online (Sandbox Code Playgroud)

java generics spring spring-mvc spring-3

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

在 Spring 中使用 setAllowedFields() 方法

我正在使用 Spring 3.2.0。我已经注册了一些自定义属性编辑器以满足一些基本需求,如下所示。

import editors.DateTimeEditor;
import editors.StrictNumberFormatEditor;
import java.math.RoundingMode;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import org.joda.time.DateTime;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.beans.propertyeditors.URLEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.WebRequest;

@ControllerAdvice
public final class GlobalDataBinder 
{
    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request)
    {
        binder.setIgnoreInvalidFields(true);
        binder.setIgnoreUnknownFields(true);
        //binder.setAllowedFields(someArray);
        NumberFormat numberFormat=DecimalFormat.getInstance();
        numberFormat.setGroupingUsed(false);
        numberFormat.setMaximumFractionDigits(2);
        numberFormat.setRoundingMode(RoundingMode.HALF_UP);

        binder.registerCustomEditor(DateTime.class, new DateTimeEditor("MM/dd/yyyy HH:mm:ss", true));
        binder.registerCustomEditor(Double.class, new StrictNumberFormatEditor(Double.class, numberFormat, true));
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
        binder.registerCustomEditor(URL.class, new URLEditor());
    } 
}
Run Code Online (Sandbox Code Playgroud)

到目前为止我已经注册了这么多编辑。其中两个DateTimeEditorStrictNumberFormatEditor通过重写各自的方法进行定制,以满足数字格式和Joda-Time的自定义需求。

由于我使用的是 Spring 3.2.0,因此我可以利用@ControllerAdvice …

spring spring-mvc propertyeditor databinder spring-3

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

如何将@RequestBody与JSONP请求一起使用?

由于集群环境中的跨域问题,我试图使用jsonp数据类型执行ajax请求。

我可以向没有@RequestBody参数映射的方法发出jsonp请求,但是当我尝试使用@RequestBody参数实现RequestMapping时,出现415不支持的媒体类型错误。

通常,当我遇到此问题时,这是由于某些属性未正确在发布的json对象与其在Spring中映射到的Java对象之间正确映射所致。但是我能找到的唯一差异是,使用jsonp会添加一个名为callback的参数和一个带有下划线“ _”的参数。

所以我在我的Java对象中添加了标签@JsonIgnoreProperties(ignoreUnknown = true),并认为应该可以解决该问题,但是仍然会引发此错误。

我还有什么需要做的吗?

编辑:我现在在Spring的调试日志输出中看到此堆栈跟踪:org.springframework.web.HttpMediaTypeNotSupportedException:内容类型'application / octet-stream'不支持

$.ajax({
  url : 'http://blah/blah.html',
  data : { abc : '123' }, (I also tried to JSON.stringify the object but no difference)
  dataType : 'jsonp',
  success : function(response) {
    alert('ok '+JSON.stringify(response));
  },
  fail : function(response) { 
    alert('error'+JSON.stringify(response));
  }
});
Run Code Online (Sandbox Code Playgroud)

Spring控制器是:

@RequestMapping({ "blah/blah" })
@ResponseBody
public ReturnObject getBlahBlah (@RequestBody MyObject obj) throws Exception {

    }
Run Code Online (Sandbox Code Playgroud)

参数对象是:

@JsonIgnoreProperties(ignoreUnknown = true)
public class MyObject {

  private String abc;
  // getter and setter for …
Run Code Online (Sandbox Code Playgroud)

java ajax jsonp spring-mvc spring-3

2
推荐指数
1
解决办法
4114
查看次数

Spring不会自动装配我的过滤器类

我有一个servlet过滤器声明如下:

@Component
public class BlahBlahFilter extends OncePerRequestFilter implements Filter {
Run Code Online (Sandbox Code Playgroud)

声明如下的属性:

@Autowired  
@Qualifier("appProperties") 
AppProperties properties;
Run Code Online (Sandbox Code Playgroud)

我在应用程序的许多组件中都有相同的Autowired声明,并且没有任何问题 - 但它们都是@Component标签的控制器,服务和其他misc内容

但是这个过滤器类被忽略了,我无法弄清楚如何让Spring将属性注入其中.

我注意到在我的调试日志文件中,这是在组件扫描期间写在此类名旁边的:

"Ignored because not a concrete top-level class" 
Run Code Online (Sandbox Code Playgroud)

咦?是的,它是一个具体的类,它不是抽象的,也不是一个接口.看起来非常腥....

我能做什么?

我看到了其他一些主题,他们绝对没有帮助.他们都没有接受答案,也没有一个帖子帮助我的情况.

其他相关的代码段可能会有所帮助:

web.xml中:

  <filter>
  <filter-name>blahBlahFilter</filter-name>
  <filter-class>com.blah.BlahBlahFilter</filter-class>
</filter>

<filter-mapping>
  <filter-name>blahBlahFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>


<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
Run Code Online (Sandbox Code Playgroud)

弹簧mvc.xml:

  <context:annotation-config/>
  <context:component-scan base-package="com.blah"/>   
  <mvc:annotation-driven/>
Run Code Online (Sandbox Code Playgroud)

java spring-mvc spring-3

2
推荐指数
1
解决办法
5100
查看次数

部署到tomcat 8.0.21和java 8时,Spring上下文初始化失败,出现java.lang.IllegalArgumentException

我的Web应用程序在JDK 1.7上正常运行但在1.8上崩溃,但有以下异常(在应用程序服务器启动时 - tomcat 8期间).我使用的是Spring版本:3.2.2.RELEASE.

我编译为目标1.7,我只将运行时改为java 8.

10-Apr-2015 10:50:44.250 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log No Spring WebApplicationInitializer types detected on classpath
10-Apr-2015 10:50:44.266 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log Initializing Spring root WebApplicationContext
10-Apr-2015 10:50:51.832 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.listenerStart Exception sending context initialized event to listener instance of class com.nrift.finch.inf.startup.web.OperationContextListener
 java.lang.IllegalStateException: application init failed
    at com.nrift.finch.inf.startup.web.OperationContextListener.contextInitialized(OperationContextListener.java:85)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4728)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5166)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:940)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1738)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalArgumentException
    at …
Run Code Online (Sandbox Code Playgroud)

spring-3 java-8 tomcat8

2
推荐指数
1
解决办法
5434
查看次数

使用Java Spring 3.0 @NumberFormat注释

我目前正在开发一个小型项目,试图让Java spring验证在Web表单上运行.它确实有效,但是我有一个用于输入年龄的输入,然后我使用这个注释转换为数字格式,如果我输入字母,它会在提交表单时将其显示在输入框旁边:

"无法将类型为java.lang.String的属性值转换为属性所需的类型java.lang.Integer;嵌套异常为org.springframework.core.convert.ConversionFailedException:无法从类型java.lang转换值"dasdf" .string类型为java.lang.Integer;嵌套异常是java.lang.IllegalArgumentException:无法解析dasdf"

有没有办法改变这个消息,我确信它很简单,但已经搜索过,找不到它.

这是目前的验证码:

@NotNull
@NumberFormat(style = Style.NUMBER)
@Min(1)        
@Max(110)        
private Integer age;
Run Code Online (Sandbox Code Playgroud)

干杯,大卫

java spring spring-annotations number-formatting spring-3

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

Spring @Transaction在抛出Exception时不回滚

我一直在寻找这个问题,在StackOverflow和Google上有很多这样的问题,但我似乎无法为我工作.

这是我的代码Spring配置:(我不使用任何切入点 - 我想我不需要?)

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
...
</bean>

<bean id="hibernateSessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
 <property name="dataSource" ref="dataSource" />
 ...
</bean>

<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="hibernateSessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
Run Code Online (Sandbox Code Playgroud)

我有一个服务类:

@Service
public class ServiceImpl implements ServiceInterface 
{
    /**
     * Injected session factory
     */
    @Autowired(required=true)
    private SessionFactory sessionFactory;

    @Autowired(required=true)
    private Dao myDao;

    /**
     * {@inheritDoc}
     */
    @Transactional(rollbackFor=Exception.class, propagation=Propagation.REQUIRED)
    public void scheduleBlast(BlastParameters blastParameters) throws ServiceException 
    {
        ... do bunch of stuff ..
        myDao.persist(entity)

        if(true)
            throw new ServiceException("random error")
    }

    .. setter methods and …
Run Code Online (Sandbox Code Playgroud)

java hibernate spring-3

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

创建名为'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0'的bean时出错

使用名称创建bean时出错

'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0' defined in URL [file:/E:/source-files-healthentic/securityadmin/build/test/classes/applicationContext.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in URL [file:/E:/source-files-healthentic/securityadmin/build/test/classes/applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Must start with Java agent to use InstrumentationLoadTimeWeaver. See Spring documentation.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0' defined in URL [file:/E:/source-files-healthentic/securityadmin/build/test/classes/applicationContext.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in URL [file:/E:/source-files-healthentic/securityadmin/build/test/classes/applicationContext.xml]: Invocation of init method failed; nested exception …
Run Code Online (Sandbox Code Playgroud)

jpa struts2 junit4 eclipselink spring-3

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