Java Spring - List

时间:2015-05-07 13:18:16

标签: java spring concurrency

我有一个当前在我的类中自动装配的对象列表,我想使用新的spring查找方法注入,这样每次调用此列表时,都会返回一个新的PROTOTYPE bean列表(我希望每个都有一个新对象)时间,因为这些是有状态bean,如果我得到相同的对象,我最终会遇到并发问题)。

以下是旧的实施:

@Service
public class Service {

@Autowired
private List<HandlersInterface> handlers;

public void run() {
    // handle the action using one of the handlers
    handlers.get(0).doSomething();
}

这样可以正常工作,但每次调用service.run()时,处理程序列表都是相同的,因此同一个处理程序可能会多次运行而导致出现问题。

转到spring查找方法注入,我找到了一些简单方案的教程,但是我找不到管理整个列表的东西。类似的东西:

@Service
public class Service {

public void run() {
List<HandlersInterface> handlers= lookUpHandlers();   
handlers.get(0).doSomething();
}

@Lookup
protected List<AppDataMessageHandler> lookUpHandlers() {
    return null; //I want this to be replaced by spring to provide a list of PROTOTYPE beans
}

}

想知道我是否应该在spring.xml文件中添加列表? (请注意,我的列表是不同的@Component bean列表,实现了一个通用接口)

1 个答案:

答案 0 :(得分:0)

我的解决方案最终是:

spring.xml

// define the structs that we are using.
typedef struct {
     int jj;
     int kk;
} s1;

typedef struct {
     int kk;
     int ii;
     int jj;
} s2;

void AssignS1 (void *a, void *b) { *((s1 *)a) = *((s1 *)b); return; }
void AssignS2 (void *a, void *b) { *((s2 *)a) = *((s2 *)b); return; }

void myFunction (void *a, void *b, void (*pFunc)(void *x, void *y))
{
     //   do stuff
     pFunc(a, b);    // do the assignment
     //   do more and more and tons of stuff
}

myFunctionUser (void)
{
    s1  a1, b1;
    s2  a2, b2;

    // do things with a1 and b1 in prep to call the function
    // do things with a2 and b2 in prep to call the function

    myFunction (&a1, &b1, AssignS1);

    myFunction (&a2, &b2, AssignS2);

    // do more stuff

}

在我班上:

// define a macro that will generate various type specific versions of a function.
#define WriteThing(s) void WriteThing##s (s *a, s *b) \
    { *a = *b;  if (a->jj != 4) { a->jj += b->jj + 10;} return; }

// define the function we will use to call the above function based on the type of the arguments
#define WriteThingCall(s,a,b) WriteThing##s (a, b)

// define the structs that we are using.
typedef struct {
    int jj;
    int kk;
} s1;

typedef struct {
    int kk;
    int ii;
    int jj;
} s2;

// generate the functions we are going to need for our different types
WriteThing(s1)

WriteThing(s2)

// example function of how to use this approach.
void func (void)
{
    s1  a1 = {0}, b1 = {0};
    s2  a2 = {0}, b2 = {0};

    WriteThingCall(s1, &a1, &b1);
    WriteThingCall(s2, &a2, &b2);

}

如果不在spring.xml中手动定义列表,我找不到办法做同样的事情