相关疑难解决方法(0)

Spring Java Config:如何使用运行时参数创建原型范围的@Bean?

使用Spring的Java Config,我需要使用只能在运行时获得的构造函数参数来获取/实例化原型范围的bean.请考虑以下代码示例(为简洁起见而简化):

@Autowired
private ApplicationContext appCtx;

public void onRequest(Request request) {
    //request is already validated
    String name = request.getParameter("name");
    Thing thing = appCtx.getBean(Thing.class, name);

    //System.out.println(thing.getName()); //prints name
}
Run Code Online (Sandbox Code Playgroud)

Thing类的定义如下:

public class Thing {

    private final String name;

    @Autowired
    private SomeComponent someComponent;

    @Autowired
    private AnotherComponent anotherComponent;

    public Thing(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }
}
Run Code Online (Sandbox Code Playgroud)

注意事项namefinal:它只能通过构造函数来提供,并保证不变性.其他依赖项是Thing类的特定于实现的依赖项,并且不应该知道(紧密耦合到)请求处理程序实现.

此代码与Spring XML配置完美配合,例如:

<bean id="thing", class="com.whatever.Thing" scope="prototype">
    <!-- other post-instantiation properties omitted --> …
Run Code Online (Sandbox Code Playgroud)

java spring scope prototype spring-java-config

121
推荐指数
4
解决办法
8万
查看次数

Spring-自动装配通用接口的通用实现

我有一个小问题。这可能是微不足道的,但我以前从未遇到过。

我有通用接口及其通用实现。我想为其自动接线,但是发生了错误。详细信息如下:

接口

@Service
public interface Serializing<T extends Serializable> {
    String serialize(T toBeSerialized);

    T deserialize(String toBeDeserialized, Class<T> resultType);
}
Run Code Online (Sandbox Code Playgroud)

实作

@Service
public class JsonSerializer<T extends Serializable> implements Serializing<T> {
   /** code **/
}
Run Code Online (Sandbox Code Playgroud)

自动接线尝试

private NoteDAO noteDAO;

@Qualifier("jsonSerializer")
private Serializing<UserComment> serializer;

@Autowired
public NoteController(NoteDAO noteDAO, Serializing<UserComment> serializer) {
    this.noteDAO = noteDAO;
    this.serializer = serializer;
}
Run Code Online (Sandbox Code Playgroud)

错误

Parameter 1 of constructor in somepackagepath.NoteController required a bean of type 'anotherpackagepath.Serializing' that could not be found.
Run Code Online (Sandbox Code Playgroud)

我想让它尽可能简单。我已经检查过Web,但是只发现了有关在配置中定义确切的bean的信息。如果可能,我宁愿避免这样做。

java generics spring autowired

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