标签: autowired

在 Symfony 中创建一个 Cache Provider 类

我们的 Symfony 3.4 应用程序上有 memcache:

cache:
    app: cache.adapter.memcached
    default_memcached_provider: "%app.memcached.dsn%"
Run Code Online (Sandbox Code Playgroud)

然而,我们被要求使用多个缓存服务器,因此仅传递一个 DSN 是不够的。

在这里(https://symfony.com/blog/new-in-symfony-3-3-memcached-cache-adapter),我看到你可以用这样的代码创建它:

$client = MemcachedAdapter::createConnection(array(
    // format => memcached://[user:pass@][ip|host|socket[:port]][?weight=int]
    // 'weight' ranges from 0 to 100 and it's used to prioritize servers
    'memcached://my.server.com:11211'
    'memcached://rmf:abcdef@localhost'
    'memcached://127.0.0.1?weight=50'
    'memcached://username:the-password@/var/run/memcached.sock'
    'memcached:///var/run/memcached.sock?weight=20'
)); 
Run Code Online (Sandbox Code Playgroud)

但是,这不是自动连接的。

我相信我们需要创建一个提供程序类,或者以某种方式让它addServer($dsn)在实例化后进行调用。我还在随机帖子中看到以下内容:

memcache:
    class: Memcached
    calls:
        - [ addServer, [ %app.memcached.dsn.1% ]]
        - [ addServer, [ %app.memcached.dsn.2% ]]
Run Code Online (Sandbox Code Playgroud)

然而它并没有真正帮助或者我错过了一些东西。

有人可以帮忙吗?我如何创建这个提供者类?

php memcached caching autowired symfony

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

为什么人们使用 @Autowired 进行构造函数注入

我看到很多人@Autowired在构造函数中使用注释来注入依赖项,如下所示

@Service
public class Employee {

 private EmployeeService employeeService;
 
 @Autowired
 public Employee(EmployeeService employeeService) {
   this.employeeService = employeeService;
 }
 :
 :
}
Run Code Online (Sandbox Code Playgroud)

据我所知,现在 Spring 非常先进,Spring 构造函数/setter DI 即使没有@Autowired如下所示也能工作

@Service
public class Employee {

 private EmployeeService employeeService;

 public Employee(EmployeeService employeeService) {
   this.employeeService = employeeService;
 }
 :
 :
}
Run Code Online (Sandbox Code Playgroud)

想知道人们是否有任何理由使用@Autowired注释来注释构造函数以注入依赖项。

有人可以帮我解决这个问题吗

java spring dependency-injection autowired

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

如何在调用构造函数之前获取注入的 spring @Value 注解值?

在 Spring 中,有一种方法可以在构造函数调用之前将 application.properties 中定义的属性连接到用 @Value 注释的相应字段。

请参阅下面的代码中我的评论。我希望该字段prop1(及其值)可供 constructor . 是否可以。同样,我希望该字段prop1(及其值)可供该方法使用getInstanceProp()。是否可以??

package com.demo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class WirableComponent {
  
  @Value("${prop1}")
  String prop1;
  
  String instanceProp = getInstanceProp(); //null - I want prop1 value to be injected before making this method call so i can use it in the method.
  
  public WirableComponent() {
    System.err.println("no-args WirableComponent Constructor invoked");
    System.err.println("value prop1: " + prop1); //null - I want prop1 value to be injected before …
Run Code Online (Sandbox Code Playgroud)

spring autowired spring-boot

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

Spring 3单元测试

我正在尝试为我的DAO类编写单元测试,但问题是我收到此错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name  'com.yeah.server.dao.UserDAOTest': Injection of autowired dependencies failed; nested   exception is org.springframework.beans.factory.BeanCreationException: Could not autowire   field: private com.yeah.server.dao.UserDAO com.yeah.server.dao.UserDAOTest.userDAO; nested   exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.yeah.server.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)

这是我的applicationContext文件

<?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:aop="http://www.springframework.org/schema/aop"
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/aop 
 http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

<bean id="hibernateTemplate"     class="org.springframework.orm.hibernate3.HibernateTemplate">
    <property name="sessionFactory">
        <ref local="sessionFactory" /> …
Run Code Online (Sandbox Code Playgroud)

junit spring hibernate autowired

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

当Sessionfactory.getCurrentSession.merge调用时,@ Aututired bean在ConstraintValidator中为null

我刚刚用Hibernate实现了Bean Validation.

如果我显式调用验证器它按预期工作,并且按预期注入连接到DB的@Autowired DAO bean.

我以前发现我需要在上面的内容之前添加以下语句.之前我已经广泛使用了@Autowired bean,但下面的语句对于由Spring管理验证器和注入ConstraintValidator的bean是必要的.

<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
Run Code Online (Sandbox Code Playgroud)

但是,当在SessionFactory.getCurrentSession.merge期间自动调用验证器时,bean为null.

如果我通过调用javax.Validation.validate直接调用验证器,它的工作原理使我认为我已正确设置了Spring配置.

我已经读过人们无法获得DAO bean @Autowired的帖子的数字,但在我的情况下,除了在合并期间调用时.

下面的日志输出显示首先直接调用验证器,然后作为合并操作的结果调用.

07.12.2011 01:58:13  INFO [http-8080-1] (FileTypeAndClassValidator:isValid) - Validating ...
07.12.2011 01:58:13  INFO [http-8080-1] (ConstraintValidatorHelper:getPropertyValue) - propertyName=className, returnValue=com.twoh.dto.PurchaseOrder
07.12.2011 01:58:13  INFO [http-8080-1] (ConstraintValidatorHelper:getPropertyValue) - propertyName=fileTypeId, returnValue=4
07.12.2011 01:58:13  INFO [http-8080-1] (QueryUtil:createHQLQuery) - select ft.id from FileType ft where ft.id = :fileTypeId and ft.fileClassName = :fileClassName
07.12.2011 01:58:13  INFO [http-8080-1] (BaseDAO:merge) - Entity: com.twoh.dto.PurchaseOrder: 1036.
07.12.2011 01:58:13  INFO [http-8080-1] (FileTypeAndClassValidator:isValid) - Validating ...
07.12.2011 01:58:13  INFO …
Run Code Online (Sandbox Code Playgroud)

spring hibernate autowired bean-validation

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

如何在春天使用@Autowired

我的spring.xml如下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:oxm="http://www.springframework.org/schema/oxm" xmlns:p="http://www.springframework.org/schema/p"
    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:component-scan base-package="com.mkyong.service" />
    <context:annotation-config />

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

我有Test1类

package com.mkyong.service;

import org.springframework.stereotype.Component;
@Component("test1")
public class Test1 {
public int i=1;
}
Run Code Online (Sandbox Code Playgroud)

我有一个App类

package com.mkyong.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.mkyong.service.Test1;

public class App 
{
    @Autowired
    Test1 test1;

    public static void main( String[] args )
    {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "spring.xml");
        App app=new App();

        System.out.println(app.test1);
    }

}
Run Code Online (Sandbox Code Playgroud)

但我得到的输出为null.我无法正确地自动装配它.我做错了什么?

java spring autowired

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

java.lang.IllegalArgumentException:启动tomcat时需要'dataSource'或'jdbcTemplate'

提出关于spring和tomcat的问题.我有以下代码

BookDAOImpl.java

@Repository
public class BookDAOImpl extends NamedParameterJdbcDaoSupport implements BookDAO {

    private class BookMapper implements RowMapper<Book> {

        @Override
        public Book mapRow(ResultSet resultSet, int rowNum) throws SQLException {
            Book book = new Book();
            book.setId(resultSet.getInt("id"));
            book.setTitle(resultSet.getString("title"));
            book.setAuthor(resultSet.getString("author"));
            book.setPublisher(resultSet.getString("publisher"));
            book.setPublicationDate(resultSet.getDate("publication_date"));
            book.setIsbn(resultSet.getString("isbn"));
            book.setAvailable(resultSet.getBoolean("available"));
            return book;
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

LibraryDataSource.java

@Component("dataSource")
public class LibraryDataSource extends DriverManagerDataSource {

    @Autowired
    public LibraryDataSource(@Value("${url}")String url, @Value("${user}")String username, @Value("${password}")String password) {
        super(url, username, password);
    }
}
Run Code Online (Sandbox Code Playgroud)

应用程序的context.xml

<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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd" 
    default-autowire="byName">

    <context:annotation-config/> …
Run Code Online (Sandbox Code Playgroud)

java spring tomcat spring-mvc autowired

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

使用自动装配字段进行Junit测试

我正在为一个类编写一系列测试用例,其中包括以下几种方法:

public ServiceResponse getListOfGroups() {
    ServiceResponse serviceResponse = new ServiceResponse();
    try{
        Slf4JStopWatch sw = new Slf4JStopWatch("GetListOfGroups", log, DEBUG_LEVEL);
        List<Group> Groups = Arrays.asList(restTemplate.getForObject(getGroupServiceURL(), Group[].class));
        sw.stop();
        serviceResponse.setData(Groups);
    } catch(ServiceException  ex) {
        serviceResponse.setErrorObject(ex.getErrorObject());
    } 

    return serviceResponse;
}
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是,restTemplate@autowired来自类的实际实现(因此在单元测试透视图中调用时返回null).我将如何为这些方法编写适当的测试用例?

这是我到目前为止所尝试的:

@Test
public void testGetListOfGroups() {
    //TODO
    ServiceResponse resp = new ServiceResponse();
    Mockito.when(uwsci.getListOfGroups()).thenReturn(resp); //uwsci is my mocked object
    assertTrue(uwsci.getListOfGroups() == resp);
}
Run Code Online (Sandbox Code Playgroud)

我觉得这会破坏单元测试的重点,因为它只是返回我告诉它的内容而不是真正做其他任何事情.

java junit spring mockito autowired

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

如何将Bean注入自定义参数解析器?

您好,我使用Spring Boot 1.3.2版本。我有一个自定义参数解析器,名称为ActiveCustomerArgumentResolver。一切都很好,resolveArgument方法工作正常,但是我无法初始化我的自定义arg的服务组件。解析器。生命周期流程有问题吗?这是我的代码:

import org.springframework.beans.factory.annotation.Autowired;
//other import statements

public class ActiveCustomerArgumentResolver implements HandlerMethodArgumentResolver {

@Autowired
private CustomerService customerService;

@Override
public boolean supportsParameter(MethodParameter parameter) {
    if (parameter.hasParameterAnnotation(ActiveCustomer.class) && parameter.getParameterType().equals(Customer.class))
        return true;
    else
        return false;
}

@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
    Principal userPrincipal = webRequest.getUserPrincipal();
    if (userPrincipal != null) {
        Long customerId = Long.parseLong(userPrincipal.getName()); 
        return customerService.getCustomerById(customerId).orNull(); //customerService is still NULL here, it keeps me getting NullPointerEx.
    } else { …
Run Code Online (Sandbox Code Playgroud)

dependency-injection autowired spring-boot

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

自动装配请求范围的bean的方法

我只是想知道是否还有其他方法可以自动装配请求范围的bean。所以现在我创建了一个beanin配置文件:

@Bean
@Scope(value=WebApplicationContext.SCOPE_REQUEST, proxyMode=ScopedProxyMode.DEFAULT)
public List<String> stringBean(){
    return new ArrayList<String>();
}
Run Code Online (Sandbox Code Playgroud)

所以通常我会自动连线applicationContext以使用bean

@Autowired
private ApplicationContext context; 

@Override
public void anyName() {
    List<String> list = (List<String>) getContext().getBean("stringBean");
}
Run Code Online (Sandbox Code Playgroud)

这完全正常。但是我不喜欢自动关联上下文和演员的需要。所以我尝试直接自动接线bean:

@Autowired
private List<String> stringBean;
Run Code Online (Sandbox Code Playgroud)

我在启动应用程序时遇到了一个异常,这也很清楚,因为未在请求启动之前创建Bean。

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'stringBean': Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request …
Run Code Online (Sandbox Code Playgroud)

spring autowired spring-boot

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