自动装配集合
你们中的大多数人可能会说我应该使用谷歌来解决这个问题,因为它很简单,但我找不到真正正确的解决方案。
我有两个会话范围的模型:Playlist
和 Track
。正如您所猜测的,播放列表包含曲目列表:
@Component
public class Playlist {
String name;
List<Track> tracklist;
@Component
public class Track {
int duration;
String artist;
我在控制器中使用 @Autowired 注释来获取播放列表。在第一个控制器中我设置了播放列表的属性,在第二个控制器中我得到了它们。播放列表的 name
属性一切正常,但 tracklist
为空。我知道我必须使用 @Resource
或 @Qualifier
之类的东西,但我不明白如何使这个注释起作用。光靠写
@Resource
private List<Track> tracks;
似乎是行不通的。 在我的 servlet-context.xml
中,这两个 bean 是这样声明的:
<bean id="track" class="com.foo.bar.models.Track" scope="session">
<aop:scoped-proxy/>
</bean>
<bean id="playlist" class="com.foo.bar.models.Playlist" scope="session">
<aop:scoped-proxy/>
</bean>
我已经看过这个 Spring 自动装配列表 但对我没有帮助,因为轨道不是通过 .xml 声明的,而是在控制器中设置的。
Most of you probably will say that I should use google for this problem, since it's quite simple, but I can't find a truly correct solution that works.
I have two session-scoped models: Playlist
and Track
. As you can guess, playlist contains a list of tracks:
@Component
public class Playlist {
String name;
List<Track> tracklist;
@Component
public class Track {
int duration;
String artist;
I use @Autowired
annotation in controllers to get the playlist. In the first controller I set the attributes of Playlist, in the second one I get them. Everything works fine with the name
attribute of Playlist, but tracklist
is null. I know that I must use something like @Resource
or @Qualifier
, but I don't understand how to make this annotations works. Simply writing
@Resource
private List<Track> tracks;
does not seems to work.
In my servlet-context.xml
the two beans are declared like this:
<bean id="track" class="com.foo.bar.models.Track" scope="session">
<aop:scoped-proxy/>
</bean>
<bean id="playlist" class="com.foo.bar.models.Playlist" scope="session">
<aop:scoped-proxy/>
</bean>
I've already look this Spring autowire a list but did not help me, since tracks are not declared via .xml but setted in a controller.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题解决了。我认为我的错误是用从服务传递的非自动连接的播放列表覆盖了控制器中的自动连接的播放列表。
控制器代码是:
服务是:
现在,我解决了从 Track 中删除
@Component
注释(如 JB Nizet 建议),修改控制器如下:和服务如下:
就像这样工作。如果您认为我没有说到重点,请告诉我。
Problem solved. I think that my error was overwriting the autowired playlist in the controller with a non-autowired one passed from a service.
The controller code was:
And the service was:
Now, I solved removing
@Component
annotation from Track (as JB Nizet suggest), modifying controller as follow:and service as follow:
Like this works. If you think that i'm not hitting the point, please tell me.