标签: autowired

Spring Autowire 原始布尔值

我的 XML 配置包括这些 bean 定义:

<bean id="abstractFormAction" class="staffing.server.action.form.AbstractFormAction" abstract="true" parent="baseAction">
    <property name="volunteerSaver" ref="volunteerSaver"/>
    <property name="emailSender" ref="emailSender"/> 
    <property name="closed" value="${form.closed}"/>
</bean>

<bean id="volunteerFormAction" class="staffing.server.action.form.VolunteerFormAction" parent="abstractFormAction">
    <property name="captchaGenerator" ref="captcha"/>
</bean>
Run Code Online (Sandbox Code Playgroud)

表示VolunteerFormAction是AbstactFormAction的具体实现,会继承AbstactFormAction的属性。

在 AbstractFormAction 中,我声明了这样的属性:

@Autowired protected VolunteerSaver volunteerSaver;
@Autowired protected EmailSender emailSender;
@Autowired protected boolean closed;
Run Code Online (Sandbox Code Playgroud)

尝试部署时出现以下异常:

org.springframework.beans.factory.BeanCreationException:创建名为“volunteerFormAction”的 bean 时出错:自动装配依赖项的注入失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:无法自动装配字段:受保护的布尔值 staffing.server.action.form.AbstractFormAction.closed; 嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException: 找不到类型 [boolean] 的匹配 bean 依赖项:预期至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}

它似乎在抱怨它找不到字节布尔值的 bean。但是,当定义了按值而不是按引用“关闭”的属性时,为什么它需要一个 bean?

java spring autowired

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

为什么我的服务会自动连线到Proxy?

嗨,我有这个课要测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/service.xml"})
public class Test {

    @Autowired private CommonService commonService;
Run Code Online (Sandbox Code Playgroud)

调试时,我在CommonService上获得一个对象,该对象的属性为SdkDynamicAopProxy。

如何在我的属性commonService上获得一个CommonServiceImp对象?

commonService

public interface CommonService {...}
Run Code Online (Sandbox Code Playgroud)

CommonServiceImp

@Service("commonService")
@Transactional("transactionManager")
public class CommonServiceImp implements CommonService {
    @Autowired private CommonDaoJdbcImp commonDao; ...}
Run Code Online (Sandbox Code Playgroud)

service.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:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:task="http://www.springframework.org/schema/task"
    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/task
    http://www.springframework.org/schema/task/spring-task-3.0.xsd">

    <import resource="/bbb-dao.xml"/>

    <context:component-scan base-package="aaa.bbb.service"/>
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- <bean id="transactionManager" class="org.springframework.transaction.jta.WebSphereUowTransactionManager" /> -->
    <tx:annotation-driven />
<task:annotation-driven />
Run Code Online (Sandbox Code Playgroud)

java proxy aop spring autowired

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

如何从运行时创建的非bean对象自动装配spring bean?

我有一些 Jpa 存储库和几个实体类。我需要为我的实体之一创建一个辅助对象。在该帮助程序中,我使用 @Autowire 来访问 Jpa 存储库。

@Entity
class A {
    @Transient
    Helper helper;

    ...

}

class Helper {
    A a;
    @Autowired
    CRepository repo;

    public Helper(A a) {
        this.a = a;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,存储库始终为空。我尝试过使用 SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this) 和 @Configurable,但它们都失败了。有人能为我提供一些提示吗?

顺便说一句,A 在剩余控制器内实例化。

谢谢!。

spring configurable autowired

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

从测试用例调用控制器时,使用自动连接组件测试控制器为空

我有一个控制器

@RestController
public class Create {

    @Autowired
    private ComponentThatDoesSomething something;

    @RequestMapping("/greeting")
    public String call() {
        something.updateCounter();
        return "Hello World " + something.getCounter();
    }

}
Run Code Online (Sandbox Code Playgroud)

我有该控制器的组件

@Component
public class ComponentThatDoesSomething {
    private int counter = 0;

    public void updateCounter () {
        counter++;
    }

    public int getCounter() {
        return counter;
    }
}
Run Code Online (Sandbox Code Playgroud)

我也对我的控制器进行了测试。

@RunWith(SpringRunner.class)
@SpringBootTest
public class ForumsApplicationTests {

    @Test
    public void contextLoads() {
        Create subject = new Create();
        subject.call();
        subject.call();
        assertEquals(subject.call(), "Hello World 2");
    }

}
Run Code Online (Sandbox Code Playgroud)

当控制器调用 时,测试失败something.updateCounter()。我得到一个NullPointerException …

java junit spring autowired spring-boot

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

Autowire 在 Spring 测试中不起作用

我创建了一个简单的 RestController,它自动连接 EntityManager 和我拥有的其他类。如果我运行我的应用程序,一切正常,自动装配被定义。现在我尝试为我的班级创建一个简单的测试:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@EnableWebMvc
@ContextConfiguration(classes = MonitoringController.class)
public class MonitoringControllerTest {

    private MockMvc mockMvc;

    @Autowired
    WebApplicationContext wac;

    @Before
    public void setup() {mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();

    }

    @Test
    public void testMonitoringIsUp()throws Exception {
        mockMvc.perform(get("/monitoring"))
                .andExpect(status().isOk());
    }
Run Code Online (Sandbox Code Playgroud)

这里开始问题,我得到错误 引起:org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为'monitoringController'的bean时出错:通过字段'em'表达的不满意的依赖;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有可用的“javax.persistence.EntityManager”类型的合格 bean:预计至少有 1 个 bean 有资格作为自动装配候选。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}

我想我错过了一些非常简单的东西。任何帮助表示赞赏。

testing spring autowired

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

Spring 服务未在主类中自动装配

这是我的 SourceRepository 类,它不会覆盖自动生成的通用 findAll() ,它返回 Iterable

package com.infostream.repositories;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;

import com.infostream.models.Source;

public interface SourceRepositoryImpl extends PagingAndSortingRepository<Source, Long>{

    Page<Source> findAll(Pageable pageRequest);

}
Run Code Online (Sandbox Code Playgroud)

这是我的服务类别:

package com.infostream.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

import com.infostream.models.Source;
import com.infostream.repositories.SourceRepositoryImpl;

@Component
public class SourcesService {
    @Autowired
    private SourceRepositoryImpl sourceRepository;

    public PageImpl<Source> getPaginatedSources(Pageable pageRequest) {
        Page<Source> searchResultPage = sourceRepository.findAll(pageRequest);
        return new PageImpl<Source>(searchResultPage.getContent(), pageRequest, searchResultPage.getTotalElements()); 
    }

    public Iterable<Source> getAllSources() {
        return sourceRepository.findAll();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我作为 Java 应用程序运行的主类。

package com.infostream.services; …
Run Code Online (Sandbox Code Playgroud)

java spring autowired spring-data-jpa spring-boot

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

Symfony 4。ParamConverter 注释冲突通过自动装配注入服务

当我尝试在 Controller 操作中使用 @ParamConverter 注释时,出现错误

"Cannot resolve argument $company of \"App\\Controller\\ProfileController::top()\": Cannot autowire service \".service_locator.0CrkHeS\": it references class \"App\\Document\\Company\" but no such service exists."
Run Code Online (Sandbox Code Playgroud)

我知道这样的服务不存在,因为我已经排除Documentservices.yaml. 我只需要从 Repostiroy 中找到一个 Company 文档对象。

这是我的控制器代码:

<?php

// src/Controller/ProfileController.php
namespace App\Controller;

use App\Document\Company;
use App\Service\DocumentManager\CompanyManager;
use FOS\RestBundle\Controller\FOSRestController;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Swagger\Annotations as SWG;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

/**
 * @Route("/profile")
 */
class ProfileController extends FOSRestController
{
    /**
     * @Route("/top/{id}")
     * @Method("GET")
     * @SWG\Response(
     *     response=200,
     *     description="Returns top profiles", …
Run Code Online (Sandbox Code Playgroud)

php autowired doctrine-orm doctrine-odm symfony4

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

自动装配存储库为空

我正在尝试在名为CacheManager的类中使用存储库。这个存储库应该从表中获取所有行。尽管使用了@Autowired 注释,它还是为空。我在哪里失踪?谢谢。

存储库

@Repository
public interface FraudCacheListRepository extends CrudRepository<FraudCacheListEntity,Integer> {
    List<FraudCacheListEntity> findAll();
}
Run Code Online (Sandbox Code Playgroud)

缓存管理器

@Component
public class CacheManager {

    private long second = 1000L;
    private long minute = second * 60;
    private long hour = minute * 60;

    private long TTL = hour;

    @Autowired
    private FraudCacheListRepository fraudCacheListRepository;

    public CacheManager() {
        getAllTables();
    }

    private void getAllTables(){
        List<FraudCacheListEntity> fraudCacheListEntities = fraudCacheListRepository.findAll();
        for (FraudCacheListEntity entity:fraudCacheListEntities) {
            System.out.println(entity.toString());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

核心控制器

@Component
@Configurable
public class CoreController {
    public ComController com;
    @Autowired …
Run Code Online (Sandbox Code Playgroud)

java repository autowired spring-boot

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

Symfony 5.1 - 无法自动装配服务

我想重构我的代码,但现在我有错误并且不明白是什么。Objectif :调用TokenService时不需要传递参数,并使用自动装配来自动装配EntityManager和Request,并且控制器调用服务时不设置它。

无法解析 App\Controller\TokenController::showTokens() 的参数 $tokenService 无法自动装配服务 App\Service\TokenService 方法 __construct() 的参数 $request 引用类 Symfony\Component\HttpFoundation\Request 但不存在此类服务。

前 :

/src/Controller/TokenController.php

<?php

namespace App\Controller;

use App\Service\TokenService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * @Route("/v1")
 */
class TokenController
{
   /** @var EntityManagerInterface $em */
    private $em;
    /** @var Request $request */
    private $request;

    /**
     * TokenService constructor.
     *
     * @param Request $request
     * @param EntityManagerInterface $em
     */
    public function __construct(Request $request, EntityManagerInterface $em)
    {
        $this->request = $request;
        $this->em = $em;
    }

    public function showTokens(Request $request, …
Run Code Online (Sandbox Code Playgroud)

php autowired symfony doctrine-orm

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

弹簧自动接线不起作用

我正在尝试将messageSourcebean 注入到我的组件类中。

这是bean xml的一部分:

<context:annotation-config />

<context:component-scan base-package="com.mattis.test"/>

<bean id="localeResolver"
      class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
    <property name="defaultLocale" value="en" />
</bean>

<bean id="messageSource"
      class="org.springframework.context.support.ResourceBundleMessageSource">
      <property name="basename" value="messages" />
</bean>
Run Code Online (Sandbox Code Playgroud)

在我的组件中,我得到了这个:

@Component
public class TestClass {

@Autowired
private MessageSource messageSource;

<-- more code goes here -->
}
Run Code Online (Sandbox Code Playgroud)

总是在我实例化TestClass时,messageSource为null。我尝试了更多的bean xml和类配置,但是它们都不起作用。

java spring autowired

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