当前位置: 首页 > 知识库问答 >
问题:

spring:@AutoWired for POJO,不由spring管理[重复]

汝楷
2023-03-14

我使用@AutoWired在POJO中注入一些服务。服务被注册为bean。

如果一旦POJO由spring管理(它也在spring配置上注册为Bean),那么我对注入的服务没有问题。

但是如果我创建了“Classic”POJO并通过“New”创建它,那么就不会注入任何服务。

我的问题:有没有可能配置spring,实现@AutoWired注入?

我使用由javaconfig配置的spring 4.0.3:

====

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.Ordered;
import org.springframework.http.MediaType;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.accept.ContentNegotiationManagerFactoryBean;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import com.tr.oauth.service.PhotoInfo;
import com.tr.oauth.service.PhotoService;
import com.tr.oauth.service.impl.PhotoServiceImpl;
import com.tr.oauth.service.oauth.ExtendedApprovalStoreUserApprovalHandler;

@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

   @Bean
    public ContentNegotiatingViewResolver contentViewResolver() throws Exception {
        ContentNegotiationManagerFactoryBean contentNegotiationManager = new ContentNegotiationManagerFactoryBean();
        contentNegotiationManager.addMediaType("json", MediaType.APPLICATION_JSON);

        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/jsp/");
        viewResolver.setSuffix(".jsp");

        MappingJackson2JsonView defaultView = new MappingJackson2JsonView();
        defaultView.setExtractValueFromSingleKeyModel(true);

        ContentNegotiatingViewResolver contentViewResolver = new ContentNegotiatingViewResolver();
        contentViewResolver.setContentNegotiationManager(contentNegotiationManager.getObject());
        contentViewResolver.setViewResolvers(Arrays.<ViewResolver>asList(viewResolver));
        contentViewResolver.setDefaultViews(Arrays.<View>asList(defaultView));
        return contentViewResolver;
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
    }

    @Bean
    public PhotoServiceUserController photoServiceUserController(PhotoService photoService) {
       PhotoServiceUserController photoServiceUserController = new PhotoServiceUserController();
       return photoServiceUserController;
    }

    @Bean
    public PhotoController photoController(PhotoService photoService) {
        PhotoController photoController = new PhotoController();
        photoController.setPhotoService(photoService);
        return photoController;
    }

    @Bean
    public AccessConfirmationController accessConfirmationController(ClientDetailsService clientDetailsService, ApprovalStore approvalStore) {
        AccessConfirmationController accessConfirmationController = new AccessConfirmationController();
        accessConfirmationController.setClientDetailsService(clientDetailsService);
        accessConfirmationController.setApprovalStore(approvalStore);
        return accessConfirmationController;
    }

    @Bean
    public PhotoServiceImpl photoServices() {
        List<PhotoInfo> photos = new ArrayList<PhotoInfo>();
        photos.add(createPhoto("1", "marissa"));
        photos.add(createPhoto("2", "paul"));
        photos.add(createPhoto("3", "marissa"));
        photos.add(createPhoto("4", "paul"));
        photos.add(createPhoto("5", "marissa"));
        photos.add(createPhoto("6", "paul"));

        PhotoServiceImpl photoServices = new PhotoServiceImpl();
        photoServices.setPhotos(photos);
        return photoServices;
    }


    @Bean
    public AdminController adminController(TokenStore tokenStore, ConsumerTokenServices tokenServices,
            ExtendedApprovalStoreUserApprovalHandler userApprovalHandler) {
        AdminController adminController = new AdminController();
        adminController.setTokenStore(tokenStore);
        adminController.setTokenServices(tokenServices);
        adminController.setUserApprovalHandler(userApprovalHandler);
        return adminController;
    }

   private PhotoInfo createPhoto(String id, String userId) {
        PhotoInfo photo = new PhotoInfo();
        photo.setId(id);
        photo.setName("photo" + id + ".jpg");
        photo.setUserId(userId);
        photo.setResourceURL("/impl/resources/" + photo.getName());
        return photo;
    }

    @Override
    public void configureDefaultServletHandling(
            DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}


-----------

import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import org.springframework.util.ClassUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;

/**
 * @author Dave Syer
 * 
 */
public class ServletInitializer extends AbstractDispatcherServletInitializer {

    @Override
    protected WebApplicationContext createServletApplicationContext() {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.scan(ClassUtils.getPackageName(getClass()));
        return context;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

    @Override
    protected WebApplicationContext createRootApplicationContext() {
        return null;
    }

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        super.onStartup(servletContext);
        DelegatingFilterProxy filter = new DelegatingFilterProxy("springSecurityFilterChain");
        filter.setContextAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher");
        servletContext.addFilter("springSecurityFilterChain", filter).addMappingForUrlPatterns(null, false, "/*");
    }

}

共有1个答案

唐兴贤
2023-03-14

是的,通过@configurable注释和一些字节码魔术,这是可能的。

Oliver Gierke是spring数据的幕后黑手,他为此创建了一篇不错的博客文章:http://olivergierke.de/2009/05/using-spring-configurable-in-three-easy-steps/http://aredko.blogspot.de/2011/02/using-configurable-in--framework.html

在SO上还有一个没有公认答案的问题:spring使用@Configurable自动生成

 类似资料:
  • 河楼 我试图配置Hibernate本地开发与HSQL数据库,但我被困在Spring不处理事务。 配置数据源,会话工厂等... 本地环境具有hibernate配置的属性文件 引发异常的代码的调用点 调用人员Dao.saveOrUpdate()后打印的堆栈跟踪 我已经尝试过的 在HibernateTransactionManager/DatasourceTransactionManager之间切换 属

  • 问题内容: 该FactoryBean的可用于以编程方式创建,这可能需要复杂的实例化逻辑的对象。 但是,似乎由所 创建 的bean 并没有成为春季管理的。这种解释正确吗?如果是这样,是否有任何不错的解决方法?包含一个简短的代码示例来说明我的问题。 ApplicationContext: 工厂实施: 工厂创建的类: 问题答案: 由创建的对象 是 由Spring管理,而不是由Spring实例化或配置。通

  • 有没有可能将Spring托管Bean连接到一个不受Spring IoC管理的类中?假设有两个类(不受Spring管理)和(由Spring管理)有没有可能将连接到中。 这是我最近遇到的一个问题,我不知道该怎么做?

  • 我试图在独立servlet容器(关键tc服务器)上部署spring-boot应用程序,但遇到了spring-boot管理页面的问题。当我使用命令运行应用程序时,我有正确的boot spring-boot admin UI页面,但是当我在tcServer上部署war时,在根路径上,我看到spring-boot admin页面中没有任何应用程序:我如何启用admin页面: jvm 1[2017.08.

  • 问题出在@Transactional中,在我的配置中spring应用程序没有使用它。我怎么能修好它? ...REST控制器没有任何事务性方法,它只使用specifiedServices加载实体。依赖集合(如果未加载到服务中)应为空。 应用程序启动程序类: 我还尝试将@Transactional添加到存储库接口中,但对我来说并不起作用 所以我从存储库中删除了@Transactional,创建了其他服

  • 问题内容: 我刚刚开始使用spring和hibernate进行项目。我的DAO图层类扩展了HibernateDaoSupport。我们没有使用注释。之前,我们使用了struts,因此我们使用了Session类提供的getTransaction,commit,rollback ..方法。我的要求非常简单,对于所有DAO类,如果有异常,则回滚,否则提交。请提出介绍spring交易管理的最简单方法。 问

  • 我正在开发一个使用Spring框架和Hibernate作为ORM的Web应用程序。我想创建一个注册和登录页面。登录时,应为特定用户创建会话(例如发送cookie等)。由于我是Spring的新手,我不知道如何完成这项工作。有人可以给我一个很好的教程吗?谢谢!

  • 1. 前言 安全管理是软件系统必不可少的的功能。根据经典的 “墨菲定律”—— 凡是可能,总会发生。如果系统存在安全隐患,最终必然会出现问题。 本节就来演示下,如何使用 Spring Boot + Spring Security 开发前后端分离的权限管理功能。 2. Spring Security 用法简介 作为一个知名的安全管理框架, Spring Security 对安全管理功能的封装已经非常完