我很难将bean自动连接到一个类中,该类作为init-param加载到OData4j的servlet中。我已经尝试了许多解决方案,包括加载时编织,但似乎无法让它正常工作,因为据我了解,作为init-param传递给servlet的类是在Spring上下文加载之前加载的。所有。下面是我配置的当前状态,是否有一种方法可以在以这种方式加载的类中进行依赖注入?最终目标是使UserDao bean自动装配ExampleProducerFactory.java(它是OData servlet的init-param)。
我试图只包含每个文件的关键部分,如果需要其他配置信息,请发表评论。
的applicationContext.xml
<context:component-scan base-package="com.project.core"/>
<context:spring-configured/>
<context:load-time-weaver weaver-class="org.springframework.instrument.classloading.SimpleLoadTimeWeaver" />
的web.xml
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<!-- read the XmlWebApplicationContext for spring -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>OData</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.resourceConfigClass</param-name>
<param-value>org.odata4j.producer.resources.ODataResourceConfig</param-value>
</init-param>
<init-param>
<param-name>odata4j.producerfactory</param-name>
<param-value>com.wildgigs.core.odata.ExampleProducerFactory</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>OData</servlet-name>
<url-pattern>/example.svc/*</url-pattern>
</servlet-mapping>
ExampleProducerFactory.java
@Configurable(autowire= Autowire.BY_NAME)
public class ExampleProducerFactory implements ODataProducerFactory {
@Autowired
private UserDao userDao;
@Override
public ODataProducer create(Properties arg0) {
InMemoryProducer producer = new InMemoryProducer("example");
List<User> users = userDao.findAll();
User[] usersArray = new User[users.size()];
users.toArray(usersArray);
final User[] usersArrayFinal = usersArray;
producer.register(User.class, Long.class, "Users", new Func<Iterable<User>>() {
public Iterable<User> apply() {
ThreadGroup tg = Thread.currentThread().getThreadGroup();
while (tg.getParent() != null)
tg = tg.getParent();
return Enumerable.create(usersArrayFinal).take(usersArrayFinal.length);
}
}, "Id");
return producer;
}
}
UserDaoImpl.java
@Repository
public class UserDaoImpl extends GenericDaoImpl<User, Long> implements UserDao, Serializable {
@Transactional(readOnly = true)
public User getByUserName(String userName) {
Query query = getSession().createQuery("FROM User where upper(userName) = :name");
query.setString("name", userName.toUpperCase());
return (User) query.uniqueResult();
}
}
答案 0 :(得分:2)
您应该使用球衣SpringServlet而不是ServletContrainer。使用它而不是在init参数中指定resourceConfig,您可以将其定义为spring bean。
答案 1 :(得分:0)
必须在spring配置中创建一个bean才能注入你的类。
<bean id="userDao" class="com.yourdomain.pacakage.UserDao">