标签: dependency-injection

打破依赖

我从未深入研究过Java.最近,我不得不处理一个我想调查的行为,因为我还没有完全理解它.

你能解释一下为什么主包不需要导入包b吗?虽然aa方法的参数是B类型.

此代码正常工作.

这种特殊情况可以看作是内联依赖注入吗?

package c;
import b.*;
public class C {
    B b=new B(); 

    public B cc(){ 
        return b; 
    }

}

package a;
import b.*; 

public class A {

    public void aa(B b) {}
}


package b; 
public class B {}



import a.A; 
import c.C; 

public class Test {

    public static void main(String[] args) {

        A a = new A(); 
        C c = new C();
        a.aa(c.cc()); 
        System.out.print("Test"); 
    }
}
Run Code Online (Sandbox Code Playgroud)

java dependency-injection

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

Guice - 如何使用绑定注释来构建对象列表

我创建了Guice绑定注释,允许我根据注释绑定一个类的两个不同实例,例如:

bind(Animal.class).withAnnotation(Cat.class).toInstance(new Animal("Meow"));
bind(Animal.class).withAnnotation(Dog.class).toInstance(new Animal("Woof"));
Run Code Online (Sandbox Code Playgroud)

我希望能够创建一个提供List方法的提供程序方法,该方法是我的一个类的依赖项,但是无法弄清楚如何使用这个注释:

@Provider
List<Animal> provideAnimalList() {
    List<Animal> animals = new ArrayList<Animal>();
    animals.add(@Cat Animal.class); // No, but this is what I want
    animals.add(@Dog Animal.class); // No, but this is what I want
    return animals;
}
Run Code Online (Sandbox Code Playgroud)

所以我假设我只能add()在List的方法中使用参数中的注释...但是没有.

我该怎么接近这个?在我看来,简单地对newAnimal类的两个实例更简单,也许这不是如何使用绑定注释.

我很感激在这种情况下最好地使用绑定注释的评论.

谢谢

dependency-injection guice

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

运行时类型的java.util.Map键和值

问题:
我试图找到地图的键和值的java类型,但不必迭代地图然后使用instanceof,即使地图是空的也想知道它.
上下文:
CKEditorConfig可以从这里下载(http://ckeditor.com/download)是使用地图实现的.但是你不能使用注入来设置这个地图,因为没有提供setter方法,并且没有提供构造函数来使用构造函数注入来设置它.但是,有五个addConfigValue方法(见下文),我可以使用它来添加这些值.

public void addConfigValue(final String key, final Number value);
public void addConfigValue(final String key, final String value);
public void addConfigValue(final String key, final Boolean value);
public void addConfigValue(final String key, final Map<String, ? extends Object> value);
public void addConfigValue(final String key, final List<? extends Object> value);
Run Code Online (Sandbox Code Playgroud)



我将在我的j2ee/java web应用程序中的几个地方使用ckeditor,所以我想我应该创建一个工厂类,它返回通过某个名称初始化编辑器所需的设置.但我想将这些配置外部化并在spring上下文文件中设置它们.因为我无法创建配置对象,所以我必须使用常规地图,然后使用地图构建配置对象.但我需要在构建对象之前验证来自spring的那些地图.

这是我构建配置对象的方法:

    @SuppressWarnings("unchecked")
    public CKEditorConfig buildConfigFromMap(Map<String, Object> configMap) {
        CKEditorConfig config = new CKEditorConfig();
        for (String key : configMap.keySet()) {
            Object val = configMap.get(key);
            if (val instanceof …
Run Code Online (Sandbox Code Playgroud)

java spring types dependency-injection map

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

注入Service Manager以在ZF2中构建Doctrine存储库

如何将服务管理器注入Doctrine存储库以允许我检索Doctrine Entity Manager?

我使用ZF2-Commons DoctrineORMModule并且正在尝试实现Doctrine Tutorial(下面链接中的教程底部)中列出的存储库示例:

http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/tutorials/getting-started.html

但是,我不断收到一条消息" 致命错误:在C:\ zendProject\zf2 ... "中的非对象上调用成员函数get(),这表明我没有服务定位器的工作实例.

我的Doctrine存储库看起来像这样:

namespace Calendar\Repository;

use  Doctrine\ORM\EntityRepository,
     Calendar\Entity\Appointment,
     Calendar\Entity\Diary;

use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class ApptRepository extends EntityRepository implements ServiceLocatorAwareInterface 
{
   protected $services;

   public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
   {
       $this->services = $serviceLocator;
   }

   public function getServiceLocator()
   {
        return $this->services;
   }

  public function getUserApptsByDate()
  {
     $dql = "SELECT a FROM Appointment a";

     $em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');

     $query = $em()->createQuery($dql);

     return $query->getResult();
   }
}
Run Code Online (Sandbox Code Playgroud)

然后,我想使用以下模式在我的控制器中调用它:

$diary = $em->getRepository('Calendar\Entity\Appointment')->getUserApptsByDate();
Run Code Online (Sandbox Code Playgroud)

编辑:附加的链接表明我可能需要将类转换为服务,
/sf/answers/945615961/

但是,如果这是最佳路线,那么我将如何让我的Doctrine Entity了解该服务.目前,我在指向该类的doc块中包含一个注释. …

service doctrine dependency-injection zend-framework2

0
推荐指数
2
解决办法
7915
查看次数

温莎为什么不解决我注册的每个装饰者?

我有一个班,我想装饰两次.但是,当我解决这个类时,Windsor只修饰它一次而不是使用我的2个装饰器.我不确定为什么会这样,因为我在我正在解析的类之前注册了两个装饰器,这就是我理解装饰器与Windsor一起工作的方式.

这是我的代码.

public interface IQueryExecuter
{
    TReturn Execute<TReturn>(IQuery<TReturn> query);
}

public class QueryLoggingDecorator : IQueryExecuter
{
    private ILogger _logger = NullLogger.Instance;

    public ILogger Logger
    {
        set { _logger = value; }
    }

    public TReturn Execute<TReturn>(IQuery<TReturn> query)
    {
        _logger.Info("Before query execute");
        var queryResults = query.Execute();
        _logger.Info("After query execute");

        return queryResults;
    }
}

public class QueryTransactionDecorator : IQueryExecuter
{
    public TReturn Execute<TReturn>(IQuery<TReturn> query)
    {
        try
        {
            Console.WriteLine("Beginning transaction");
            var queryResults = query.Execute();
            Console.WriteLine("Comitting transaction");

            return queryResults;
        }
        catch (Exception)
        {
            Console.WriteLine("Rolling back …
Run Code Online (Sandbox Code Playgroud)

dependency-injection castle-windsor

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

如何在不使用Spring IOC的情况下在JSF托管bean中注入服务

通常,如果我必须在Spring中注入服务,我会使用

 <bean id="mycontroller" class="com.MyController">
    <property name="myService" ref="myService" />
Run Code Online (Sandbox Code Playgroud)

<bean id="myService" class="com.MyService"></bean>
Run Code Online (Sandbox Code Playgroud)

使用JSF时如何做同样的事情?我不想为bean使用两个IOC容器,而是将它保存在faces context本身.我见过像这样的链接

JSF 2使用@ManagedProperty注入Spring bean/service而没有xml

以及将spring bean注入jsf bean的问题.他们谈论将Spring托管bean注入JSF上下文.我想要做的事情必须非常简单,但无法找到任何相关信息.我是新手,将会感激任何帮助.

jsf spring dependency-injection

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

在JUnit测试中使用Mock类和依赖注入

我有一个基本接口,另一个类正在实现.

package info;

import org.springframework.stereotype.Service;

public interface Student 
{
    public String getStudentID();
}
Run Code Online (Sandbox Code Playgroud)

`

package info;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

@Service
public class StudentImpl implements Student
{
    @Override
    public String getStudentID() 
    {
        return "Unimplemented";
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我有一个服务来注入该类

package info;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Service
public class InfoService {

    @Autowired
    Student student;

    public String runProg()
    {
            return student.getStudentID();
    }
}
Run Code Online (Sandbox Code Playgroud)

我想知道的是,如何设置JUnit测试,以便Student接口的Mock类使用stubbed方法而不是StudentImpl中的方法.注入确实有效但我想使用amock类来模拟结果而不是为了测试.任何帮助将不胜感激.

junit spring dependency-injection mockito

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

TinyIoC返回相同的实例

我是依赖注入模式的新手,我在从容器中获取类的新实例时遇到问题.在tinyioc中解析它只是继续返回相同的实例而不是新实例.现在为代码

public abstract class HObjectBase : Object
{
    private string _name = String.Empty;
    public string Name 
    {
        get
        {
            return this._name;
        }
        set
        {
            if (this._name == string.Empty && value.Length > 0 && value != String.Empty)
                this._name = value;
            else if (value.Length < 1 && value == String.Empty)
                throw new FieldAccessException("Objects names cannot be blank");
            else
                throw new FieldAccessException("Once the internal name of an object has been set it cannot be changed");
        }
    }

    private Guid _id = new Guid(); …
Run Code Online (Sandbox Code Playgroud)

dependency-injection tinyioc

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

有益于接线豆

我们正在做一个相当复杂的项目,它可以访问多个数据源.目前,我们最多可以进行64次Web服务交易,并期望增加更多.我们定义了一个服务层和一个DAO.服务层类通常具有一个或多个DAO类,用于查找数据.DAO类使用spring xml连线连接到服务层类.

DAO类都有一个接口和一个Impl.这里的关键是只有一个Impl.虽然impl可能会改变,但即使这样也不太可能,因为DAO层来自一个稳定的遗留系统.

那么如果只有一个impl,那么弹簧接线的好处是什么?为什么不在服务层类中实例化类?

java spring dependency-injection

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

调用其类方法时,Spring依赖注入得到了NullPointException

我有以下Java类,它有一个dao由构造函数args注入的字段:

public class FeatureFormationFromRaw {

    private MyDAOImpl dao;   //field to be injected from beam.xml

    public FeatureFormationFromRaw(MyDAOImpl dao) {
        //do a fresh clean and save all data, dependency injection by constructor args
        dao.removeAll();          //This is fine.
        dao.saveDataAll();        // This is fine.
    }


    public float calcuFeatures(String caseName) {

        List<JSONObject> rawData = dao.getData(caseName);    //This line throws NullPointException because dao=null here.
                .........
    }

    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        FeatureFormationFromRaw featureForm = (FeatureFormationFromRaw) context.getBean("featureFormation");

        float value = …
Run Code Online (Sandbox Code Playgroud)

java spring dependency-injection nullpointerexception

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