Java 如何在eclipse动态web项目中设置资源目录?

Java 如何在eclipse动态web项目中设置资源目录?,java,eclipse,spring,location,classpath,Java,Eclipse,Spring,Location,Classpath,我想构建一个使用最少库的web项目。我所做的就在下面 在Eclipse(Luna)中创建动态Web项目 配置为Maven项目 并在pom.xml中导入一些库 实现WebApplicationInitializer 我做了两个配置类和初始化器,看起来像 RootConfig.java要替换“root context.xml” @Configuration public class RootConfig { @Value(value="${jdbc.driverClassName}")

我想构建一个使用最少库的web项目。我所做的就在下面

  • 在Eclipse(Luna)中创建动态Web项目
  • 配置为Maven项目
  • 并在pom.xml中导入一些库
  • 实现
    WebApplicationInitializer
我做了两个配置类和初始化器,看起来像

RootConfig.java
要替换“root context.xml”

@Configuration
public class RootConfig {

    @Value(value="${jdbc.driverClassName}")
    private String jdbcDriverClassName;

    @Value(value="${jdbc.url}")
    private String jdbcUrl;

    @Value(value="${jdbc.username}")
    private String jdbcUsername;

    @Value(value="${jdbc.password}")
    private String jdbcPassword;

    private static final String RESOURCE_LOCATION = "resources";

    @Bean
    public static PropertyPlaceholderConfigurer propertyPlaceholder() {
        PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
        Resource[] resources = new ClassPathResource[]{ 
                new ClassPathResource(RESOURCE_LOCATION + File.separator + "properties"
                        + File.separator + "jdbc" + File.separator + "jdbc.properties")
        };
        ppc.setLocations(resources);
        return ppc;
    }

    @Bean
    public DataSource dataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(this.jdbcDriverClassName);
        dataSource.setUrl(this.jdbcUrl);
        dataSource.setUsername(this.jdbcUsername);
        dataSource.setPassword(this.jdbcPassword);
        return dataSource;
    }
};
@Configuration
@EnableWebMvc
@EnableAsync
@ComponentScan(
    basePackages= {
            "com.gosports.api.controller"
            , "com.gosports.common.controller"
            , "com.gosports.test.controller"
    }
    , excludeFilters=@ComponentScan.Filter(Configuration.class)
)
public class ServletConfig extends WebMvcConfigurerAdapter {

    @Bean
    public ViewResolver viewResolver () {
        InternalResourceViewResolver vResolver = new InternalResourceViewResolver();
        vResolver.setPrefix("/WEB-INF/views/");
        vResolver.setSuffix(".jsp");
        return vResolver;
    }
}
这是
ServletConfig.java
,假设它将取代“servlet context.xml”

@Configuration
public class RootConfig {

    @Value(value="${jdbc.driverClassName}")
    private String jdbcDriverClassName;

    @Value(value="${jdbc.url}")
    private String jdbcUrl;

    @Value(value="${jdbc.username}")
    private String jdbcUsername;

    @Value(value="${jdbc.password}")
    private String jdbcPassword;

    private static final String RESOURCE_LOCATION = "resources";

    @Bean
    public static PropertyPlaceholderConfigurer propertyPlaceholder() {
        PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
        Resource[] resources = new ClassPathResource[]{ 
                new ClassPathResource(RESOURCE_LOCATION + File.separator + "properties"
                        + File.separator + "jdbc" + File.separator + "jdbc.properties")
        };
        ppc.setLocations(resources);
        return ppc;
    }

    @Bean
    public DataSource dataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(this.jdbcDriverClassName);
        dataSource.setUrl(this.jdbcUrl);
        dataSource.setUsername(this.jdbcUsername);
        dataSource.setPassword(this.jdbcPassword);
        return dataSource;
    }
};
@Configuration
@EnableWebMvc
@EnableAsync
@ComponentScan(
    basePackages= {
            "com.gosports.api.controller"
            , "com.gosports.common.controller"
            , "com.gosports.test.controller"
    }
    , excludeFilters=@ComponentScan.Filter(Configuration.class)
)
public class ServletConfig extends WebMvcConfigurerAdapter {

    @Bean
    public ViewResolver viewResolver () {
        InternalResourceViewResolver vResolver = new InternalResourceViewResolver();
        vResolver.setPrefix("/WEB-INF/views/");
        vResolver.setSuffix(".jsp");
        return vResolver;
    }
}
最后,我的初始值设定项

public class WASInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext arg0) throws ServletException {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(RootConfig.class);
        context.register(ServletConfig.class);

        context.setServletContext(arg0);
        Dynamic servlet = arg0.addServlet("dispatcher", new DispatcherServlet(context));
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);
    }
};
自从我把我的'jdbc.properties'文件放在
/{project_location}/src/resources/properties/
中后,它就开始工作了

但是我想做的是将这个文件放到
/WEB-INF/resources/properties/
中。 我不能绝对路径在代码中,考虑分布

我需要引用project server中的关系位置。有一些方法可以通过
HttpServletRequest
ServletContext
找到该目录,但我不能这样做,因为那些部分-
propertyPlaceholder()
part-是静态方法

有什么好的例子或解决方案可以做到这一点吗? 我真的不想使用Spring模板或xml。 有没有可能我只想用java文件做什么


感谢您的回答:D

您可以获得线程#getContextClassLoader()返回的类加载器

/WEB-INF文件夹不在类路径的根目录中,而是在其/WEB-INF/classes文件夹中,您需要从其中加载与类路径相关的属性文件

classLoader.getResourceAsStream("/jdbc.properties");
或者你也可以把它们当作永远有用的资源来阅读

AppServiceClass.class.getClassLoader().getResourceAsStream("/jdbc.properties");

首先,您不应该再使用
PropertyPlaceholderConfigurer
,而应该使用
propertysourcesplaceplaceholderconfigurer
。接下来,不要自己加载文件,只需在类上使用
@PropertySource
。将文件放入
src/main/resources
中,然后maven将其添加到类路径中

@Configuration
@PropertySource("classpath:/properties/jdbc/jdbc.properties")
public class RootConfig {

    @Bean
    public static PropertySources PlaceholderConfigurer propertyPlaceholder() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

这假设您创建的目录结构中的所有属性都位于
src/main/resources
中。

谢谢您的回答:D

但也许我的解释还不够,所以我必须找到出路。下面是我为动态Web项目设置资源文件夹的解决方案

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    // TODO Auto-generated method stub
    //super.addResourceHandlers(registry);
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/").setCachePeriod(31556926);;
}   

坦率地说,我一直理解到
addResourceLocations
,但没有提到
setCachePeriod
。这是我一直在寻找的解决方案

只要把它放在原处,并在前面加上
classpath:
@M.Deinum谢谢。如果你不介意的话,我想再问一个问题。如何在静态方法中打印
类路径:
?我还经常在config.xml中使用该关键字。但是在Java类中。。。我不知道。它只是一根线,没什么大不了的。你在想复杂的。。。另请看我的答案。谢谢你的回答:D。但是如果你不介意的话,我想再问一个问题。您说过我不应该再使用
属性PlaceHolderConfigure
。我想知道原因。我访问了文档页面,但我发现其中一个方法已被弃用,而不是整个类。再次感谢。我认为这个答案应该是正确的。所以我接受了这个答案。然而,我想要的有点不同,所以我也在下面添加了一条评论。我希望我的答案能帮助像我这样的年轻开发者。b
属性资源占位符配置器
属性PlaceHolder配置器
功能强大得多。后者仅对通过属性文件或系统属性加载的属性进行操作。但是,属性源更加灵活,它可以使用系统环境、系统属性、servletcontext、jndi、属性文件或任何适合用作
属性源的内容。谢谢您的好意!