Defining spring security http element in two different files? - spring

Is it possible to define the security:intercept-url elements and security:custom-filter elements for a single security:http in two different Spring configuration files?
This is so we can cleanly reuse the security:custom-filter definitions which will be common across many applications with intercept rules that will not.
I can't simply duplicate the <security:http> element because I get BeanDefinitionParsingException: Configuration problem: Duplicate <http> element detected. I am well well aware of how to split a normal bean file with import

As requested in comment:
Spring Security versions prior to 3.1.x do not allow multiple http element definitions.
3.1 does however.
Here is the Jira issue for the feature.
This article on 3.1 changes might also be helpful.
You can define another context file in your web.xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-contexts/context1.xml
/WEB-INF/spring-contexts/context2.xml
</param-value>
</context-param>
Or you can define a directory where your contexts would be and name them any way you like without having to specify each context file separately:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-contexts/*
</param-value>
</context-param>
Regarding Ayusman's answer, you actually can import your security contexts into your bean contexts:
<beans>
<import resource="classpath*:/security-context-*.xml"/>
<bean><!-- blah blah --></bean>
</beans>

use the import in application context file..
custom-filter.appcontext.xml
.
.
<import resource="interceptor-url-file.xml"/>
Note that both files need to have the proper spring xml schema details and MUST be valid XML files.

I have been working on this error for 5 hours. Really stupid problem.
This error is a parse error that when you comment some lines in applicationContext-security.xml, files are not generated correctly.
Let me explain on an example code.
<port-mappings>
<port-mapping http="7001" https="7002" />
</port-mappings>
<!-- <port-mappings>
<port-mapping http="7015" https="7515" />
</port-mappings>
-->
this lines are generated as,
<port-mappings>
<port-mapping http="7001" https="7002" />
</port-mappings>
<port-mappings>
<port-mapping http="7015" https="7515" />
</port-mappings>
-->
so that, compiler tells you "duplicate element detected". Because generated file includes duplicate elements.
I hope to help you .

Related

context:component-scan, why do I have to scan multiple times?

I'm trying to clear up some Spring concepts here. I have two contextConfigureLocation xml files as defined in web.xml here
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-datasource.xml
/WEB-INF/security.xml
</param-value>
</context-param>
So, in the first configuraton file "spring-datasource.xml", I did a component-scan like so
<context:annotation-config />
<context:component-scan base-package="com.mycompany.root" />
my source code structure is like so
com
--->mycompany
--------------->root
--------------------->ui
--------------------->server
--------------------->etc
The issue is, my controllers decorated with #controllers under "com.mycompany.root.ui" never got picked up.
in the spring-servlet.xml, I had to do another componet-scan like so
<context:annotation-config />
<context:component-scan base-package="com.mycompany.root.ui" />
<mvc:resources mapping="/images/**" location="/images/" />
<mvc:annotation-driven />
<mvc:default-servlet-handler/>
for my controllers to get picked up.
Why is that? I thought whatever higher up in the parent configuration files should automatically be avaialbe to the children configuraton file? Or is that not the case as evident here.
[EDit] - After some reading, I think I'm more curious with controllers instantiated in the root application context, what happened to them when the spring-dispatch servlet got to them? The child applicaton context just ignored them? It will be nice if anyonne can show me some source code of dispatch servlet that did the ignore.
Thanks

Eclipse Spring MVC Project Configuration Files

I have created a Spring MVC project through eclipse. I believe I used some plugins to generate the project directory. I find here there configuration files.
web.xml
root-context.xml
servlet-context.xml
I am kinda of familiar with Spring MVC & its dependency injection. However I have problems understanding the last two configuration files (root-context & servlet-context).
What kind of configurations do they contain?
Also in may online examples I see mvc-dispatcher-servlet.xml. Why did eclipse not generate this xml file in my project?
[IMPORTANT] I wanted to set up strong security and user authentication for my web app. I have been following online tutorials again and they all create a seperate
xml file named spring-security.xml and add the namespace information to that file. Does it suffice if I just create this file and add the name space information? I mean
dont' I need to import this file to a main file that is scanned by Spring framework?
How do I define and where do I put spring application context.xml file and start wiring the dependencies together? Also if I define everything (all dependencies here) how is this file picked up by the framework?
Thanks,
Configuration Files
If you check your web.xml you will find both of root-context.xml and servlet-context.xml files being referred here. One used by Dispatcher Servlet and other by Context Loader Listenter. You can name your files to whatever unless they are being refereed in web.xml
Eclipse Not generating files
Every editor works its own way. some may generate full fledged project/app with both DispatcherServlet and ContextLoaderListner configured or some with only DispatcherServlet ( with minimal configutaion). Check Spring Roo it starts with basic and gives you the flexibility to generate a strong app.
mvc-dispatcher-servlet.xml is not there
Some of the thing in spring projects are convention based, for example if you are not providing any file to your DispatcherServlet in web.xml spring looks for mvc-dispatcher-servlet.xml file, and if you have provided it won't look for.
Spring Security
To Configure Spring Security you need to provide at least some configuration. But the question is where. You need to add this configuration to your web.xml only. and Hence no need to import this to any other file.
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener- class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/spring-security.xml
</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Where to define application context.xml
Just define it any where, configure beans in it.
You can add this file as follows:
a) Either Import this into some other configuration file like root-context.xml or servlet-context.xml
as <import resource="application-context.xml"/>
b) Add this into web.xml with ContextLoaderListner as context param
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:META-INF/spring/application-context*.xml
classpath*:META-INF/spring/abc*.xml
</param-value>
</context-param>

environment specific log4j configuration by spring

I am loading log4j.xml using the traditional way
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:conf/log4j.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
This works fine but now I need to load a different log4j.xml file based on which environment I am in which is defined by a environment variable/jndi entry .. so I was hoping that with new spring 3.1 property management I could just change this to
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:conf/log4j-${ENV-NAME}.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
and spring will load the correct log4j file in each environment but this doesnt works probably because web.xml is loaded before spring. I came across this method
<bean id="log4jInitialization" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetClass" value="org.springframework.util.Log4jConfigurer" />
<property name="targetMethod" value="initLogging" />
<property name="arguments">
<list>
<value>log4j-${ENV-NAME}.xml</value>
</list>
</property>
</bean>
so essentially moving configuration of log4j into spring context file instead of web.xml. But this doesnt works either for some reason logging gets enabled in a way that everything is logged. So how can I use a different log4j.xml file based on an environment variable or loading it programmatically in the servletcontextlistener.
It's too late to help adeelmahmood, but hope others will benefit from my answer.
The thing is adeelmahmood was right, this configuration:
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:conf/log4j-${ENV-NAME}.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
is working, but:
Log4jConfigListener should be registered before ContextLoaderListener in web.xml !!!
You must also remember that Log4jConfigListener assumes an expanded WAR file.
Then, if ENV-NAME environment variable is set, it works as expected.
By the way, ${ENV-NAME} can be used in spring config files as well! That's not everything... You can also use our env.property to set spring profile:
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>${ENV-NAME}</param-value>
</context-param>
This way you can set log4jConfigLocation and spring profile, both with one and the same env. variable.
BTW and just in case: using Maven profiles to have separate builds for dev, test and production isn't good practice. Read eg. http://java.dzone.com/articles/maven-profile-best-practices and remember: "Use profiles to manage build-time variables, not run-time variables and not (with RARE exceptions) alternative versions of your artifact".
This might help too for more recent readers: in Log4j 2.7 (but it's probably older) the parameter name has been altered:
see interface Log4jWebSupport :
/**
* The {#link javax.servlet.ServletContext} parameter name for the location of the configuration.
*/
String LOG4J_CONFIG_LOCATION = "log4jConfiguration";
By default, Spring Boot picks up the native configuration from its default location for the system (such as classpath:logback.xml for Logback), but you can set the location of the config file by using the logging.config property.
logging.config=classpath:log4j-<ENV-NAME>.xml
https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/html/howto-logging.html

Reading 1 bean from other bean defined in different xml file in different directory

How can we read one from other bean defined in a different xml file in a different directory. For example, if there is a bean defined in
src\main\resources\serviceconfig\org\project\core_spring\file1.xml
that needs to reference another bean defined in
src\main\java\org\project\core\commons\persistence_spring\file2.xml
Is there any way to reference it or to import the resources of file2.xml into file1.xml?
Specifying the whole relative classpath as in
<import resource="\org\project\core\commons\persistence_spring\file2.xml" />
solved the issue for me.
Still haven't tried the answer given by Chao though. Would be great if that one works because entering relative path and importing some resource everytime I need to refer to it can be quite cumbersome.
You can import file2.xml into file1.xml. Using
<import resource="classpath:file2.xml" />
After importing you can use bean defined in file2.xml in file1.xml.
you can use the <context-param> tag in web.xml to include multiple bean definition files in your application. You can refer to both contexts both on the classpath or in your web folder. and you will be able to use the beans defined in those files as if they were defined in one file.
For example:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:/com/your-company/file1.xml
/WEB-INF/file2.xml
</param-value>
</context-param>

Split Application Context File in Spring

I would like to have step-by-step information on :
how to split the ApplicationContext file (eg.: myapp-servlet.xml) into multiple XML files in Spring with some examples ?
I have tried configuring web.xml with "ContextLoaderListener" and have contextConfigLocation like :
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value> /WEB-INF/business-services.xml </param-value>
</init-param>
but it is creating problems.
Please give me in-detail explaination on how to do this.
Thanks in advance !
What I like to do, if I have multiple context files, is to have my base context class import the other pieces via the import tag.
<import resource="applicationContext-otherStuff.xml"/>
We typically use this model, to keep out datasource configuration separate from the bean instantiations.
e.g. with:
<param-value>classpath*:spring/persistence/*.xml, classpath*:spring/*.xml</param-value>
the paths depend on your locations of the splitted .xml
Example with WEB-INF Directories
<param-value>/WEB-INF/daoContext.xml /WEB-INF/applicationContext.xml</param-value>
sidenote: seems to work without ','
Reference:
spring doc chapter: 3.8.5. Convenient ApplicationContext instantiation for web applications

Resources