标签: autowired

Spring自动装配的成员可见性

在Spring 3.0.x文档中,它提到当你使用非setter/config方法进行依赖注入ie.Property或Constructor时,它应该声明为私有而不是公共

例如.班级Abc

{

@Autowired
private Def def;     //DEF may be a class or an Interface.
...
....

}
Run Code Online (Sandbox Code Playgroud)

但我正在尝试使用Spring 2.5.5并尝试将其公开并且它有效... ni无法弄清楚为什么它可以工作虽然它必须表现出像Exception抛出的一般感觉

我是Spring Dependency的新手,请告诉我春天网站上的任何其他资源,我可以从中获得很好的例子来学习Spring DI

java spring visibility autowired

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

Spring自动装配和类继承

我在使用@Autowired工作时遇到了问题.对不起,如果我搞砸了任何条款,我对Spring来说相对较新.

Spring Version是3.0.5.RELEASE,我在bean定义中使用context:component-scan.

这适用于@Autowired注释:

@Component
public class UserDao {
    @PersistenceContext
    protected EntityManager em;

    @Transactional
    public User findById(Long id) {
        return em.find(User.class, id);
    }
}
Run Code Online (Sandbox Code Playgroud)

这不适用于@Autowired注释:

@Component
public class UserDao implements Dao<User> {
    @PersistenceContext
    protected EntityManager em;

    @Transactional
    public User findById(Long id) {
         return em.find(User.class, id);
    }
}
Run Code Online (Sandbox Code Playgroud)

通过这个设置,我已经添加了'实现Dao',我得到了一个:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [web.rs.persistence.dao.UserDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
Run Code Online (Sandbox Code Playgroud)

以下是一些其他类供参考:

Dao.java(界面):

public interface …
Run Code Online (Sandbox Code Playgroud)

inheritance spring autowired

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

Spring将数据源bean注入或自动装配到类

这可能是一个非常新手的问题,但我已经搜索过,或者我的理解中存在很大差距,或者我做错了一些我无法弄清楚的事情.

在我的上下文文件中,这是一个摘录

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${datasource.driverClassName}" />
    <property name="url" value="${datasource.url}" />
    <property name="username" value="${datasource.username}" />
    <property name="password" value="${datasource.password}" />
</bean>

<bean id="myBeanOne" class="a.b.c.myBeanOne">
         <property name="dataSource" ref="dataSource" />
</bean>
Run Code Online (Sandbox Code Playgroud)

现在在myBeanOne我有:

private DataSource dataSource;

private JdbcTemplate jdbcTemplate;

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

public void myMethod() {
    String sql = "'My generic SQL update query'";
    try {
        this.jdbcTemplate.update(sql);
    } catch (org.springframework.dao.EmptyResultDataAccessException ex) {
    }
    System.exit(0);
}
Run Code Online (Sandbox Code Playgroud)

当我尝试在调用setDataSource的行上执行此操作时,我收到此错误:

ERROR org.springframework.integration.handler.LoggingHandler 
    org.springframework.integration.MessageHandlingException: 
       java.lang.NullPointerException
Run Code Online (Sandbox Code Playgroud)

在线上: this.jdbcTemplate.update(sql);

我尝试了十种不同的配置来实现这一点,但我似乎无法做到这一点.非常感谢您的帮助,谢谢. …

java spring jdbc autowired

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

Spring 3 Autowired BeanInitializationException

@Autowired我遇到了一个很大的问题,那就是异常返回

bean的初始化失败; 嵌套异常是org.springframework.beans.factory.BeanInitializationException:bean'A'需要属性'serviceFactory'

以下是所有内容的简要说明(我使用的是Spring 3.2,并且我已将所有jar放在正确的位置WEB-INF/lib).

applicationContext.xml中

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

<context:annotation-config />
<context:component-scan base-package="com.sc" />

<!-- Comment out - we are going to use @Component @Autowired - 2014-01-07
<bean id="A" class="com.sc.A">
  <property name="serviceFactory" ref="serviceFactoryBean" />
</bean> 
-->

<bean id="serviceFactoryBean" class="com.sc.ServiceFactory" autowire="byName" />

</beans>
Run Code Online (Sandbox Code Playgroud)

com.sc.A类的内容

@Component
public class A
{

private Logger logger = Logger.getLogger(A.class);

// @Autowired -- 2014-01-07 comment out as not need it since annotation in setter below
// @Qualifier("serviceFactoryBean")
private ServiceFactory serviceFactory;

public …
Run Code Online (Sandbox Code Playgroud)

spring autowired required

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

在@Autowire调用期间未实例化服务类

我试图在我的消息传递应用程序中使用@Service类,但是当我从泛型类中尝试时,该类不会通过@Autowire实例化.它只在我使用Controller时实例化.

这是我的控制器:

    package hello;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import hello.Application;

@Controller
public class HelloController {


    @Autowired
    private MessageSender sender;

    @RequestMapping(value="/", method=RequestMethod.GET)
    public String index() {
        return "index";
    }

    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Greeting greeting(HelloMessage message) throws Exception {
        System.out.println("Sending message...");
        beginRoute(message.getName());
        sender.greet("thunder");
        return new Greeting("Hello, " + message.getName() + "!");
    }

    public void beginRoute(String message) {
        Application.startBody(message);
    }
}
Run Code Online (Sandbox Code Playgroud)

上述对sender.greet的调用是成功的.

这是我尝试使用该服务的另一个类:

package com.routing.integration;

import hello.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessageSendingOperations; …
Run Code Online (Sandbox Code Playgroud)

java spring stomp autowired spring-boot

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

如何在事务类上自动装配?

班级档案:

@Transactional(propagation=Propagation.REQUIRES_NEW)
public class ServiceImpl implements Service {
...
}
Run Code Online (Sandbox Code Playgroud)

Xml文件:

...
<bean id="service" class="com.sky.core.engine.impl.ServiceImpl">
...
Run Code Online (Sandbox Code Playgroud)

测试文件:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("testConfig.xml")
public class ServiceImplTest {

    private static final Logger log = Logger
            .getLogger(ServiceImplTest.class);

    @Autowired
    private ServiceImpl service;

    @Test
    public void test(){
       ...
    }
Run Code Online (Sandbox Code Playgroud)

例外:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.sky.core.engine.comp.impl.ServiceImplTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.sky.core.engine.impl.ServiceImpl com.sky.core.engine.impl.Service; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.sky.core.engine.comp.impl.ServiceImpl] found for dependency: expected at …
Run Code Online (Sandbox Code Playgroud)

java spring hibernate autowired

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

自动插入其余依赖项时,@ InjectMocks不起作用

我正在尝试ClassA使用2服务的测试。一种服务需要自动连线,而另一种则被视为模拟对象。不幸的是,嘲笑的对象是

没有注射

参加我的测试班。所有字段的行为都像我只会使用spring自动装配功能来进行设置一样。经过测试的ClassA也从其他抽象类继承。如果不使用自动装配,则模拟对象将成功传递。不幸的是,我无法嘲笑ServiceDao,这就是为什么我尝试合并 @InjectMocks@Autowiring注释的原因。

A级

public ClassA extends AbstractClassA<ClassOne, ClassTwo>{

   @Autowired
   protected ServiceOne serviceOne;      //this services needs to be mocked

   @Override
   protected List<ClassTwo> testedMethod(){
      return serviceOne.getList();      //here method is not returning mocked objects 
   }                                    //as it supposed to do.
     ........
}
Run Code Online (Sandbox Code Playgroud)

抽象类

public class AbstractClassA<T1 extends InterfaceOne, T2 extends InterfaceTwo){
    @Autowired
    protected ServiceDAO serviceDAO; //this services needs to be autowired

    protected abstract List<T2> testedMethod();

}
Run Code Online (Sandbox Code Playgroud)

TestClass。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:testApplicationContext.xml"})
public class Test {
    @Mock …
Run Code Online (Sandbox Code Playgroud)

junit spring mocking mockito autowired

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

预选赛不在春季工作

CallingApp.java

@Service
@ComponentScan(basePackages = { "com.codegeekslab.type" })
public class CallingApp {

    @Autowired
    @Qualifier("BasicPhone")
    private Phone phone;

    public CallingApp(Phone phone) {
        this.phone = phone;
    }

    public void makeCall(int number) {
        phone.openApp(number);
    }

}
Run Code Online (Sandbox Code Playgroud)

Phone.java

package com.geekslab.device;

public interface Phone {

    public void openApp(int number);

}
Run Code Online (Sandbox Code Playgroud)

BasicPhone.java

package com.codegeekslab.type;

import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.geekslab.device.Phone;
@Component("BasicPhone")
 public class BasicPhone implements Phone {
    {
        System.out.println("BasicPhone");
    }

    public void openApp(int number) {
        System.out.println("calling via simcard... " + number);
    }

}
Run Code Online (Sandbox Code Playgroud)

SmartPhone.java

package …
Run Code Online (Sandbox Code Playgroud)

java spring qualifiers autowired

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

如何在Spring MVC中自动连接多级继承类

在我的项目中,我有三个类,它们通过多级继承相关联

@Component
@Scope("prototype")
class A{


}

@Component
@Scope("prototype")
class B extends A{

}

@Component
@Scope("prototype")
class C extends B{

}   
Run Code Online (Sandbox Code Playgroud)

现在通过使用@Autowired注释我想在Manager类中使用C类 Object

@Component(value = "manager")
@Scope("prototype")
class Manager {

@Autowired
A a;

@Autowired
B b;

@Autowired
C c;

......
}
Run Code Online (Sandbox Code Playgroud)

这里AB类对象是由弹簧容器注入的,但是在为C注入Object时,它正在抱怨如下

nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.abc.bca.generator.sss.B] is defined: expected single matching bean but found 2: b,c
Run Code Online (Sandbox Code Playgroud)

当我将@Qualifier用于C类时

@Autowired
@Qualifier('c')
C c 
Run Code Online (Sandbox Code Playgroud)

要么

@Autowired
@Qualifier('c')
B c …
Run Code Online (Sandbox Code Playgroud)

java spring spring-mvc autowired

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

根据命令行参数注入实现

有没有办法在Spring Boot中基于​​命令行参数注入特定的接口实现?

我有一个数据加载应用程序,并根据命令行参数我需要加载特定类型的数据.

这是我的主要课程CommandLineRunner:

@SpringBootApplication
public class DataLoadersApplication implements CommandLineRunner {

    private Type1LoadProcess type1LoadProcess;
    private Type2LoadProcess type2LoadProcess;

    public DataLoadersApplication(Type1LoadProcess type1LoadProcess,
      Type2LoadProcess type2LoadProcess) {
        this.type1LoadProcess = type1LoadProcess;
        this.type2LoadProcess = type2LoadProcess;
    }

    public static void main(String[] args) {
        SpringApplication.run(DataLoadersApplication.class, args);
    }

    @Override
    public void run(String... args) {
        if (args[0].equalsIgnoreCase("load-type1")) {
            type1LoadProcess.process();
        } else if (args[0].equalsIgnoreCase("load-type2")) {
            type2LoadProcess.process();
        } 
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法DataLoadeProcess用两个实现创建一个接口,Type1DataLoadProcessType2DataLoadProcess根据命令行arg在main类中注入实现?

java command-line interface autowired spring-boot

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