标签: autowired

清洁代码 - 应用@Autowired应该在哪里?

我将从一个简单的例子开始.你有一个Spring启动应用程序,它CommandLineRunner在初始化时运行一个类.

// MyCommandLineRunner.java
public class MyCommandLineRunner implements CommandLineRunner {
    private final Log logger = LogFactory.getLog(getClass());
    @Autowired //IntelliJ Warning
    private DataSource ds;
    @Override
    public void run(String... args) throws Exception {
        logger.info("DataSource: " + ds.toString());
    }
}
// Application.java
@SpringBootApplication
public class Application {
    public static void main(String... args) {
        SpringApplication.run(Application.class, args); 
    }
    @Bean
    public MyCommandLineRunner schedulerRunner() {
        return new MyCommandLineRunner();
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,像这样,这个工作,一切都很好.但是,IntelliJ会在哪里发出警告@Autowired(我在评论中标记了哪里)

Spring团队建议:始终在bean中使用基于构造函数的依赖注入.始终使用断言来强制依赖.

现在如果我遵循这个,我有一个基于构造函数的依赖注入

@Autowired
public MyCommandLineRunner(DataSource ds) { ... }
Run Code Online (Sandbox Code Playgroud)

这也意味着我必须编辑Application.java,因为构造函数需要一个参数.在Application.java …

java spring coding-style autowired spring-boot

14
推荐指数
2
解决办法
8991
查看次数

@Autowired HttpServletResponse

我正在寻找一种自动装配的方法HttpServletResponse.它不适用于开箱即用的弹簧,但我发现了这种描述.这有点令人讨厌,因为那个春天显然有一个机制来让对象请求作用域(即HttpServletRequest),这似乎是一个劈开顶部的黑客.

有没有办法挂钩弹簧用于的相同机制HttpServletRequest?而且,任何想法为什么春季团队决定只能使HttpServletRequestautowire能够(并被排除在外HttpServletResponse)?

java spring spring-mvc autowired

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

如何在使用new创建的对象中在spring中自动装配对象

我想要做的就是在NotesPanel类中自动连接字段backgroundGray,但我得到的只是下面的例外.

那么,问题是,如何正确地自动装配它?它真的让我发疯,因为它可能是非常愚蠢的我做错了...

谢谢你的帮助!托尔斯滕

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'notepad' defined in class path resource [Beans.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [notepad.Notepad]: Constructor threw exception; nested exception is java.lang.NullPointerException
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [notepad.Notepad]: Constructor threw exception; nested exception is java.lang.NullPointerException
Caused by: java.lang.NullPointerException
    at notepad.NotesPanel.<init>(NotesPanel.java:23)
    at notepad.Notepad.<init>(Notepad.java:18)
Run Code Online (Sandbox Code Playgroud)

类记事本:

package notepad;

import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.JFrame;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Notepad …
Run Code Online (Sandbox Code Playgroud)

java spring autowired

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

如何将记录器注入示例Spring启动应用程序中的字段?

我想要的是让spring autowire成为记录器.所以,换句话说,我想让这个工作:

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MainController {

    @Autowired
    private Logger logger;

    @RequestMapping("/")
    public String enterSite(HttpServletResponse response) {
        logger.info("site entered");
        return "welcome";
    }
}
Run Code Online (Sandbox Code Playgroud)

现在它在启动时抛出异常:"找不到类型[org.slf4j.Logger]的限定bean用于依赖...".

我的pom.xml依赖项:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.0.M1</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency> …
Run Code Online (Sandbox Code Playgroud)

java logging spring autowired spring-boot

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

如何在Spring测试期间创建CrudRepository接口的实例?

我有一个Spring应用程序,在其中我使用xml配置,只使用Java Condfig.一切都还可以,但是当我尝试测试时,我遇到了在测试中启用组件的问题.所以让我们开始我有一个界面

@Repository
public interface ArticleRepository extends CrudRepository<Page, Long> {
    Article findByLink(String name);
    void delete(Page page);
}
Run Code Online (Sandbox Code Playgroud)

和组件/服务

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleRepository articleRepository;
...
}
Run Code Online (Sandbox Code Playgroud)

我不想使用xml配置,因此对于我的测试,我尝试仅使用Java配置测试ArticleServiceImpl.所以为了测试目的,我做了:

@Configuration
@ComponentScan(basePackages = {"com.example.core", "com.example.repository"})
public class PagesTestConfiguration {


@Bean
public ArticleRepository articleRepository() {
       // (1) What to return ?
}

@Bean
public ArticleServiceImpl articleServiceImpl() {
    ArticleServiceImpl articleServiceImpl = new ArticleServiceImpl();
    articleServiceImpl.setArticleRepository(articleRepository());
    return articleServiceImpl;
}
Run Code Online (Sandbox Code Playgroud)

}

articleServiceImpl()我需要把实例articleRepository(),但它是一个接口.如何使用新关键字创建新对象?是否可以在不创建xml配置类的情况下启用自动装配?在测试期间仅使用JavaConfiguration时可以启用awtow吗?

java xml spring spring-mvc autowired

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

Spring @Autowired混乱(容器或会话)

在我的应用程序中,我使用自动连接User到我的服务的bean,MyService并将其用作登录用户信息的原则(因此用户不是从xml作为静态bean而是从登录用户动态生成)如果有登录的十个用户我将有十个该@AutoWired User领域的候选人.(对吗?)我可以在Spring容器中找到其中任何一个cos AutoWired,而不是会话.

告诉我,如果我错了.以及如果可能的话如何实际解决它.但是如果我的AutoWired字段被注释了怎么办呢@Scope ("Session")

像这样 :

@Component("user")
@Scope("session")
public class User 
{
String userid;
String name;
//getter setters etc
}
Run Code Online (Sandbox Code Playgroud)
@Component
public class MyService
{
    @Autowired
    private User user;

}
Run Code Online (Sandbox Code Playgroud)

当我调用MyServiceComponent 时,是否可以获取其他用户的User bean .Cos MyService只是@Component即使它User@Scope(session).

基本上,(如果我的假设是错的)我认为当你@Autowire是一个字段时,它会将容器视为整体并且容器不会被分成每个会话的子容器.

spring annotations dependency-injection autowired

12
推荐指数
2
解决办法
9885
查看次数

Spring Data Repository自动装配失败

我正在研究这个问题很长一段时间,并且无法让它发挥作用.希望你们中的一些人可以不遗余力地帮助我.

这个场景
我建立它使用Spring MVC的Web应用程序.这个webapp应该使用另一个包含持久层的Maven项目.持久层当前仅由服务和Spring Data存储库组成.持久层本身可以对抗本地MySQL实例.

我的问题
我对持久层进行了JUnit测试.测试加载并保存实体.这是通过服务处理的.两种操作都很好.

现在我在webapp的Maven项目中的JUnit测试中尝试相同的操作.我再次尝试保存并加载实体.但这次失败了.Spring声明服务中的Repository引用无法自动装配,因为没有适合的bean.

我尝试过多种方法来解决这个问题.例如,使用直接布线,给出限定符等.我的方法都没有奏效.我甚至构建了两个完整的新Maven项目,我简化了场景,但保留了必要的元素.在那里,它像一个魅力.我不明白我在这个上做错了什么,因为我调整了工作示例中的设置.


持久性项目 persistence.xml中的文件

 <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
          http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
          http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd" default-autowire="byName">

    <tx:annotation-driven transaction-manager="transactionManager" />
    <context:annotation-config />

    <context:component-scan base-package="com.company.dev.webapp" />
    <jpa:repositories base-package="com.company.dev.webapp.repository" query-lookup-strategy="create-if-not-found" />

    <bean id="exceptionPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

    <!-- Data Source -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" >
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost/webapp" />
        <property name="username" value="root" />
        <property name="password" value="" />
        <property name="initialSize" value="20" />
    </bean>

    <!-- Hibernate -->
    <bean …
Run Code Online (Sandbox Code Playgroud)

java spring autowired

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

如何自动装配Spring TaskExecutor创建的线程?

根据Spring的文档,使用TaskExecutor的方法如下:

import org.springframework.core.task.TaskExecutor;

public class TaskExecutorExample {

  private class MessagePrinterTask implements Runnable {

    private String message;

    public MessagePrinterTask(String message) {
      this.message = message;
    }

    public void run() {
      System.out.println(message);
    }

  }

  private TaskExecutor taskExecutor;

  public TaskExecutorExample(TaskExecutor taskExecutor) {
    this.taskExecutor = taskExecutor;
  }

  public void printMessages() {
    for(int i = 0; i < 25; i++) {
      taskExecutor.execute(new MessagePrinterTask("Message" + i));
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,如果MessagePrinterTask具有自动连接的依赖关系,它们将不会被Spring配置,因为我们在Spring的上下文之外实例化我们的bean(至少我理解它是这样),即使Spring将提供实际的线程创建.如果MessagePrinterTask具有自动连接的依赖关系,我们如何让Spring识别它们?我尝试了以下修改示例无效(是的,正确启用了自动装配):

import org.springframework.core.task.TaskExecutor;

public class TaskExecutorExample {

  @Component
  private class MessagePrinterTask implements Runnable { …
Run Code Online (Sandbox Code Playgroud)

java spring multithreading autowired

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

在Cobertura仪表课的情况下,Spring @Autowired失败了

Cobertura仪器在特定情况下打破弹簧自动装配.有谁知道如何解决这个问题?

脚本

  • 我使用cobertura-maven-plugin版本2.5.1运行MVN 3.0.4.
  • mvn测试没有问题
  • mvn编译,包等也运行没有问题.
  • mvn cobertura:cobertura也没有遇到任何问题,直到添加了2个新功能,这些功能引入了许多新类,包括两个新的com.mycompany.executor执行器类.(示例:除了现有的MyExecutor之外还添加了MyHappyExecutor和MySadExecutor)
  • 从cobertura仪器过程中排除MyExecutor似乎可以修复自动装配
  • 检查弹簧自动装配输出确认正确的bean正在自动装配.

失败点

尝试在myService中自动装配myExecutor的已检测版本时,自动装配失败.在添加MyHappyExecutor和MySadExecutor之前,此工作正常.MyHappyExecutor和MySadExecutor是自动装配的,并且仅在MyExecutor中使用.

我已经附加了下面的异常输出.请注意,类和包名称已被编辑.

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myService': Injection of autowired dependencies failed; 
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.mycompany.executor.MyExecutor com.mycompany.service.impl.MyServiceImpl.myExecutor; 
nested exception is java.lang.IllegalArgumentException: Can not set com.mycompany.executor.MyExecutor field com.mycompany.service.impl.MyServiceImpl.myExecutor to $Proxy20
Run Code Online (Sandbox Code Playgroud)

结论

Cobertura仪表过程中的某些东西会影响Springs的自动装配.

更新1

强制CGLIB类代理将错误类型更改为"java.lang.NoClassDefFoundError"错误.这会影响标准测试目标以及Cobertura目标.

<aop:config proxy-target-class="true"/>
Run Code Online (Sandbox Code Playgroud)

更新2

以下是有关3个类的弹簧启动过程的输出.

2012-11-01 16:21:51 INFO  [main] Overriding bean definition for bean 'myExecutor': replacing [Generic bean: class [com.mycompany.executor.MyExecutor]; scope=; abstract=false; lazyInit=false; autowireMode=1; dependencyCheck=0; autowireCandidate=true; …
Run Code Online (Sandbox Code Playgroud)

spring instrumentation cobertura autowired maven

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

在给出NoSuchBeanDefinitionException的构造函数上@Autowired(required = false)

在Spring应用程序中,我使用@Autowired(required=false)了构造函数.这意味着如果要自动装配的bean在xml文件中不可用,则NoSuchBeanDefinitionException应该抛出no,因为required=false提到了().但我得到的UnsatisfiedDependencyException,NoSuchBeanDefinitionException例外.

- - 文本编辑器

public class TextEditor {

    private SpellChecker x;
    private String name;    

    @Autowired(required=false)
    public TextEditor(SpellChecker x) {
        System.out.println("Inside TextEditor constructor." );
        this.x = x;
    }


    public SpellChecker getY() {
        return x;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void spellCheck() {
        x.checkSpelling();
    }
}
Run Code Online (Sandbox Code Playgroud)

- - 拼写检查程序

public class SpellChecker {
    public SpellChecker() {
        System.out.println("Inside SpellChecker constructor."); …
Run Code Online (Sandbox Code Playgroud)

spring autowired

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