MDP*_*MDP 6 java spring spring-mvc
我有一个名为Menu的类,注释为@Entity,我需要在名为GestoreMessaggi的类中使用一个方法
....
@Component
@Entity
@Table(name="menu")
public class Menu implements Serializable{
@Autowired
@Transient // because i dont' save this field on the DB
private GestoreMessaggi gestoreMessaggi;
.....
public void setCurrentLanguage(){
/* I got the error both if use gestoreMessaggi
this way and if I use the autowired istance of GestoreMessaggi*/
GestoreMessaggi gestoreMessaggi = new GestoreMessaggi();
gestoreMessaggi.gest();
}
.....
Run Code Online (Sandbox Code Playgroud)
这是GestoreMessaggi类的相关代码
@Component
public class GestoreMessaggi {
@Autowired
private ReloadableResourceBundleMessageSource messageSource;
public void gest(){
messageSource.doSomething() <--- here messageSource is null
}
}
Run Code Online (Sandbox Code Playgroud)
什么时候,我打电话给gestoreMessaggi.gest(); 从Menu类,我收到一个错误,因为messageSource为null.gestoreMessaggi istance不为null,仅为messageSource为null
重要提示:只有当我从注释为@Entity的类中调用GestoreMessaggi时,才会在messageSource上获取null .
在ds-servlet.xml中,我告诉Spring扫描包含Menu和GestoreMessaggi类的pakages:
//Menu package
<context:component-scan base-package="com.springgestioneerrori.model"/>
//Gestore messaggi package
<context:component-scan base-package="com.springgestioneerrori.internazionalizzazione"/>
Run Code Online (Sandbox Code Playgroud)
谢谢
您可以遵循两种方法:
@Entity类的方法中获取Spring管理的bean的实例如果你选择选项1,你必须显式访问Spring的上下文并检索你需要的bean实例:
@Component
public class Spring implements ApplicationContextAware {
private static final String ERR_MSG = "Spring utility class not initialized";
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static <T> T bean(Class<T> clazz) {
if (context == null) {
throw new IllegalStateException(ERR_MSG);
}
return context.getBean(clazz);
}
public static <T> T bean(String name) {
if (context == null) {
throw new IllegalStateException(ERR_MSG);
}
return (T) context.getBean(name);
}
}
Run Code Online (Sandbox Code Playgroud)
您需要让Spring扫描此类才能使其正常工作.
然后,在你的内部@EntityClass,这样做:
public void setCurrentLanguage(){
GestoreMessaggi gestoreMessaggi = Spring.bean(GestoreMessaggi.class);
gestoreMessaggi.gest();
}
Run Code Online (Sandbox Code Playgroud)
这就是全部.请注意,你就不需要自动装配GestoreMessaggi成你的@Entity了.另请注意,Spring和大多数社区都不推荐这种方法,因为它将您的域类(您的@Entity类)与Spring类耦合.
如果你选择选项2,那么你需要做的就是让Spring像往常一样解决自动装配,但是在你的实体之外(例如在dao或服务中),如果你的实体需要你填写一些消息或其他什么,只需在其上调用一个setter.(那取决于你的要求,取决于你@Entity的属性@Transient与否取决于你).