标签: autowired

Spring Boot - 环境@Autowired抛出NullPointerException

我使用Spring Boot 0.5.0.M5进行项目设置.

在我尝试的其中一个配置文件中,@Autowire Environment但是失败了NullPointerException.

这是我到目前为止所拥有的:

Application.java

@EnableAutoConfiguration
@Configuration
@ComponentScan
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

JpaConfig.java想去的地方@Autowire Environment

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.ui.persistence.repository")
public class JpaConfig {
    private static final String DATABASE_DRIVER = "db.driver";
    private static final String DATABASE_PASSWORD = "db.password";
    private static final String DATABASE_URL = "db.url";
    private static final String DATABASE_USERNAME = "db.username";
    private static final String HIBERNATE_DIALECT = "hibernate.dialect"; …
Run Code Online (Sandbox Code Playgroud)

java environment nullpointerexception autowired spring-boot

17
推荐指数
4
解决办法
5万
查看次数

Spring DI - REST服务中的Autowired属性为null

我正在开始使用Spring DI,但我正在努力使用依赖注入,更糟糕的是我甚至不确定为什么对我来说似乎没问题.希望你们能帮助我!

问题是注释为@Autowired的属性始终为null

我有一些Maven结构的项目:

  • com.diegotutor.lessondeliver
  • com.diegotutor.utility

我在Tomcat 7上运行示例

我正在使用以下依赖项pom.xml:

  • 春天语境3.2.4
  • spring-web 3.2.4
  • 泽西服务器1.17.1
  • jersey-core 1.17.1
  • jersey-servlet 1.17.1

简单的想法是拥有一个RESTful服务,通过依赖注入能够打印位于以下位置的配置文件中的属性的值: D:\configuracion.conf.

com.diegotutor.utility我有以下界面:

package com.diegotutor.utility;

public interface ConfigService {

    public String getProperty(final String propertyName);
}
Run Code Online (Sandbox Code Playgroud)

实施者:

package com.diegotutor.utility.impl;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.Properties;

import com.diegotutor.utility.ConfigService;

public class PropertyFileConfigService implements ConfigService{

Properties prop;

public PropertyFileConfigService (final InputStream input) throws IOException {
    if(input == null) {
        throw new IllegalArgumentException("Input stream can't be null"); …
Run Code Online (Sandbox Code Playgroud)

spring dependency-injection jersey nullpointerexception autowired

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

Spring @Autowired是按名称还是按类型注入bean?

我正在读初春(威利出版社)的书.在第2章中有一个关于Java配置的例子@Autowired.它提供了这个@Configuration

@Configuration
public class Ch2BeanConfiguration {

    @Bean
    public AccountService accountService() {
        AccountServiceImpl bean = new AccountServiceImpl();
        return bean;
    }

    @Bean
    public AccountDao accountDao() {
        AccountDaoInMemoryImpl bean = new AccountDaoInMemoryImpl();
        //depedencies of accountDao bean will be injected here...
        return bean;
    }

    @Bean
    public AccountDao accountDaoJdbc() {
        AccountDaoJdbcImpl bean = new AccountDaoJdbcImpl();
        return bean;
    }
}
Run Code Online (Sandbox Code Playgroud)

和这个普通的bean类

public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }
    ...
} …
Run Code Online (Sandbox Code Playgroud)

java configuration spring code-injection autowired

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

从Gradle自动装配BuildProperties bean - NoSuchBeanDefinitionException

我试图从Gradle构建文件中获取Java应用程序中的版本.我按照这里的指示行事;

https://docs.spring.io/spring-boot/docs/current/reference/html/howto-build.html

的build.gradle

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-
        plugin:1.5.7.RELEASE")
    }
}

project.version = '0.1.0'

apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'

springBoot  {
    buildInfo()
}

jar {
    baseName = 'ci-backend'
}

war {
   baseName = 'ci-backend'
}

repositories {
    mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    compile("org.springframework:spring-jdbc")
    compile("joda-time:joda-time")

    compile("com.opencsv:opencsv:3.9")
    compile("org.springframework.batch:spring-batch-core")

    testCompile('org.springframework.boot:spring-boot-starter-test')
    providedRuntime('org.springframework.boot:spring-boot-starter-tomcat')
 }
Run Code Online (Sandbox Code Playgroud)

使用gradle构建后,该build-info.properties文件存在于build/resources/main/META-INF/build-info.properties中

在我,@RestController我试图自动装配构建属性bean

@Autowired
private BuildProperties buildProperties;
Run Code Online (Sandbox Code Playgroud)

我收到以下错误;

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: …
Run Code Online (Sandbox Code Playgroud)

spring autowired gradle spring-boot

17
推荐指数
4
解决办法
7448
查看次数

@Autowire默认模式

Spring @Autowirebean:byName还是byType?如果不可能,是否使用其他模式进行了第二次试验?

spring autowired

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

@Autowired对象在一个类中获取空值,而在另一个类中成功连接

我正在使用Spring 3和Spring Security开发一个项目.我的问题是IoC容器.当我UserDetailsService为Spring Security-3 编写自己的实现时问题就出现了.我检查了其他问题,但仍无法解决问题.

问题的定义是:

我有两个单独的类(一个是UsersController.java扩展的@Controller,ProjectUserDetailsService哪个扩展@Service),它使用一个公共对象进行自动装配.但是当对象成功自动装入时UsersController,它就nullProjectUserDetailsService类中,尽管这个类(ProjectUserDetailsService)的对象已成功创建(我通过调试验证了这一点).

有什么建议如何解决这个问题?

这里是我的web.xml,project-servlet.xml而且project-security.xml文件和相关的类.

Web.xml`

<?xml version="1.0" encoding="UTF-8"?>
<!--
  - Tutorial web application
  -
  -->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name>Ecognitio with Spring Security</display-name>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
            /WEB-INF/ecognitio-servlet.xml
            /WEB-INF/ecognitio-security.xml
        </param-value>
  </context-param>
  <context-param>
    <param-name>webAppRootKey</param-name>
    <param-value>tutorial.root</param-value>
  </context-param>
  <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <listener>
    <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
  </listener> …
Run Code Online (Sandbox Code Playgroud)

spring spring-mvc autowired

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

Spring Autowiring仅适用于Interface

我对spring框架很新,遇到了以下问题.

我有一个接口ClassA,由分类ClassA1ClassA2.

我添加了以下bean定义 applicationContext.xml

<bean id="class1" class="com.abc.ClassA1" />
<bean id="class2" class="com.abc.ClassA2" />
Run Code Online (Sandbox Code Playgroud)

我想将两个实现类Autowire如下所示.

@Autowired
private ClassA1 classA1;

@Autowired
private ClassA2 classA2;
Run Code Online (Sandbox Code Playgroud)

上面的代码抛出错误为

无法自动写入字段:com.abc.ClassA1 com.abc.SomeClass.classA1; 嵌套异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:没有匹配的[com.abc.ClassA1]类型的bean

但是,如果我将自动装配更改为接口,如下所示:

@Autowired
ClassA classA1;
Run Code Online (Sandbox Code Playgroud)

然后ClassA1自动连接到变量.我无法知道如何将变量自动装配到ClassA2.

java spring autowired

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

从单元测试中注入模拟Spring @Autowired依赖项的最佳方法是什么?

import org.springframework.beans.factory.annotation.Autowired;

class MyService {
  @Autowired private DependencyOne dependencyOne;
  @Autowired private DependencyTwo dependencyTwo;

  public void doSomething(){
    //Does something with dependencies
  }
}
Run Code Online (Sandbox Code Playgroud)

在测试这个类时,我基本上有四种注入模拟依赖项的方法:

  1. 在测试中使用Spring的ReflectionTestUtils来注入依赖项
  2. 向MyService添加构造函数
  3. 将setter方法添加到MyService
  4. 放宽对包受保护的依赖性可见性并直接设置字段

哪个最好,为什么?

---更新---

我想我应该更清楚一点 - 我只是谈论"单元"样式测试,而不是Spring"集成"样式测试,其中依赖关系可以使用Spring上下文连接.

java spring dependency-injection mocking autowired

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

Spring @autowired不适用于非单件容器吗?

我有一个MyTask实现的类,Runnable并且可以在任何给定时刻实例化许多这样的对象.有些属性我想自动MyTask上课.

但我认为,如果我MyTask@Component它标记它将成为一个弹簧管理的单身正确吗?这不是我想要的,我需要由TaskExecutor运行这个类的许多独立实例.

所以我的问题:

  • a)我对@Component注释的理解从根本上是错误的吗?它不会MyTask成为一个由春季管理的单身人士吗?
  • b)我应该使用其他注释,以便spring检测@Autowired并注入属性吗?
  • c)弹簧自动装配不适用于非单件容器/类MyTask吗?

更新#1 - 这些不起作用:

public class MyTask implements Runnable { // I want this class to be non-singleton
    @Autowired
    public SomeSpecialSpringConfiguredConnectionClass blah; // this is the singleton bean that should be injected
    @Override
    public void run() {
        // BLAH IS NULL, this shouldn't be NULL, that is not what I want
        // which makes sense …
Run Code Online (Sandbox Code Playgroud)

singleton spring spring-aop autowired

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

无法自动装配.找不到SimpMessagingTemplate类型的bean

我基本上按照文档中提供的指南在Spring中配置Websockets.

我正在尝试从服务器向客户端发送消息,如 " 从任何地方发送消息 " 一节中所述

在示例之后,您可以自动装配名为SimpMessagingTemplate的类

@Controller
public class GreetingController {

    private SimpMessagingTemplate template;

    @Autowired
    public GreetingController(SimpMessagingTemplate template) {
        this.template = template;
    }

    @RequestMapping(value="/greetings", method=POST)
    public void greet(String greeting) {
        String text = "[" + getTimestamp() + "]:" + greeting;
        this.template.convertAndSend("/topic/greetings", text);
    }

}
Run Code Online (Sandbox Code Playgroud)

但是,我当前的项目找不到bean"SimpMessagingTemplate".(Intellij:'无法自动装配.没有找到SimpMessagingTemplate类型的bean'.

我在互联网上查了几个例子,但是我找不到如何让Spring创建一个SimpMessagingTemplate实例.我怎样才能自动装配它?

编辑:

我决定发送更多背景信息.这是我目前的websocket配置:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:websocket="http://www.springframework.org/schema/websocket"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/websocket
        http://www.springframework.org/schema/websocket/spring-websocket-4.0.xsd">

        <!-- TODO properties to be read from a properties file -->
        <websocket:message-broker application-destination-prefix="/app">
            <websocket:stomp-endpoint path="/new_session" >
                <websocket:sockjs/>
            </websocket:stomp-endpoint>
            <websocket:simple-broker prefix="/topic"/>
        </websocket:message-broker> …
Run Code Online (Sandbox Code Playgroud)

java stomp javabeans autowired spring-messaging

16
推荐指数
3
解决办法
3万
查看次数