I have developed a Spring MVC web application. In this application I have two containers and the location of the spring bean configuration file is:
/WEB-INF/dispatcher-servlet.xml
I have changed the name of the spring bean cfg file but I also want to change the location to:
/com/nt/cfg/applicationContext.xml
However, Spring is not recognizing any location other than /WEB-INF/
You just need to declare de route when you create the ClassPathXmlApplicationContext:
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
The default location is the resources folder.
Hope this help you.
The answer is YES, you can change the name and location of the configuration file but you have to make spring aware of the new name and location.
ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
It will load the context from context.xml file (context.xml should be present in classpath).
You can create new Applicationcontext by passing desired XML file as parameter to constructor.
So after changing name and location of the file you have to register here for spring reference so that spring can find the configuration file.
Related
I am trying to externalize my ignite configuration in my spring boot application so the configuration can be changed without rebuilding the jar.
Previously the file resided in src/main/resrouces and was loaded via annotations.
#ImportResource("IgniteConfig.xml") and
#Autowired
private IgniteConfiguration cfg;
When I moved the IgniteConfig.xml to the config folder that resides next to the excutable jar the above stopped working and I have tried the following without success:
use --spring.config.location argument. I can tell this is picked up during run time as other configurations work but the above ImportResource annotation says the file IgniteConfig.xml cannot be found.
use a relative path to (e.g. ./config.IgniteConfig.xml) to Ignition.start. I cause this relative path to print the file contents of the xml file in my logs but when I pass it to Ignition.start it says the file cannot be found. I have tried using relative and absolute paths to do this.
Manually create an ApplicationContext and get the configuration by bean name.
ApplicationContext context = new ClassPathXmlApplicationContext("./config/IgniteConfig.xml");
This again complains that the file does not exist even though I can see by opening the file directly:
File igniteConfigFile = new File("./config/IgniteConfig.xml");
The comment by konqi in this post answered my question:
"In case you want to import a resource that is outside the classpath the syntax would be:
#ImportResource( { "file:path/spring-context1.xml", "file:path/spring-context2.xml" } )
"
In my case I just needed to do:
#ImportResource( { "file:./config/IgniteConfig.xml" } )
I have a pretty simple servlet setup with
Jersey
no web.xml
Tomcat 9
Maven for creating the .war and handling dependencies
Now I need to deploy a test and a production version of the servlet on the server and I a trying to use the individual context.xml file for each environment. A quote from the docs
Individual Context elements may be explicitly defined:
In individual files (with a ".xml" extension) in the $CATALINA_BASE/conf/[enginename]/[hostname]/ directory. The context path and version will be derived from the base name of the file (the file name less the .xml extension). This file will always take precedence over any context.xml file packaged in the web application's META-INF directory.
All this also sounds easy here:
To give an example: if we wanted to deploy three installations of an application for test, stage and production, we would create three context.xml files:
tomcat/conf/catalina/localhost/test.xml
tomcat/conf/catalina/localhost/stage.xmltomcat/conf/catalina/localhost/prod.xml
And then deploy the same .war file three times as:
tomcat/webapps/test.war
tomcat/webapps/stage.war
tomcat/webapps/prod.war
And each installation would pick up its specific configuration automatically.
You can also read this documentation:
For Tomcat 5.0.x and later, WTP 2.0.x and later offers the opportunity to write the contexts to separate XML files in the proper folder (typically conf/Catalina/localhost) according to the requirements of that particular version. This behavior is enabled by checking the Publish module contexts to separate XML files option in the Server Options section of the Tomcat server editor. Note that only contexts for added projects will be written to separate XML files. Manually added contexts in server.xml will remain there.
There are several instructions, how to retrieve a value from the context.xml. For example:
<Environment name="companyName" value="My Company, Incorporated" type="java.lang.String" />
Can be used by
InitialContext context = new InitialContext();
Context xmlNode = (Context) context.lookup("java:comp/env");
String companyName = (String) xmlNode.lookup("companyName");
But this was listed for a Spring setup, how can this be done in a Jersey ResourceConfig based application/servlet?
For example:
#ApplicationPath("/")
public class MyMain extends ResourceConfig {
private final Logger logger = LoggerFactory.getLogger(MyMain.class);
public MyMain() {
try {
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
String myEnv = (String) envCtx.lookup("my-env");
this.logger.debug("Env: {}", myEnv);
} ...
is running into NamedExceptions: javax.naming.NameNotFoundException: Name [my-env] is not bound in this Context. Unable to find [my-env].
Is there any way to get the context configuration with Jersey, or do I need to use a different approach?
I also have no clue, how to debug the InitialContext. So the file is there and it is read by Tomcat, but I don't know how I can access it in the application. Do I need to use ServletContext.getInitParameter() instead - and how?
Update
My Eclipse setup seems to be the problem, because the published xml file is not the original, individual context.xml in my /Catalina/localhost folder. Is there any way to make sure that the original file is published in the Eclipse-Tomcat server?
"Publish module contexts to separate XML files" is checked. What is Update context paths? in publishing options (no effect visible, though)?
Here is the :
So I have the following use case-
I need to customize the bootstrap context to read the uri where the config Server lies from a particular file and then inject that uri into the property spring.cloud.config.uri to get properties from the configServer.
I have been looking at documentation on Spring cloud commons and have experimented around customizing Bootstrap property sources. This, unfortunately does not work, because this acts as another source of properties for the application context, not a source of properties for the bootstrap context( bootstrap.yml or properties).
The only solution I have so far, which is probably not the most elegant one is to set the uri property as a system property before we run the spring Application.
So, something like the following.
public static void main(String args[]) {
* Read properties from file and set as system properties*
System.setProperty("uri","http://localhost:8097");
SpringApplication.run(Application.class,args);
}
And then reference the above property in bootstrap.properties as-
spring.cloud.config.uri=${uri}
This works and is okay,but i would like to do this still in a more Spring Friendly way.
Thank you in advance.
Unfortunately this cant be done.
You can change the location of bootstrap.yml/properties using config
spring.cloud.bootstrap.location
But , you cannot add a bean to read properties which will be part of the Bootstrap context, as the Bootstrap Context will be the parent of the most senior ancestor created by the user himself.
I think you can use run arg arguments and give a defult value like this:
spring.cloud.config.uri=${config.uri:http://localhost:8097}
java jar xxx.jar --config.uri=http://localhost:8099
I am learner of spring have build my test project with spring IOC container and have configure beans.xml in my project root path and load into my application and get bean from it.
spring.xml in project root directory
BeanFactory bean = new XmlBeanFactory(new FileSystemResource("spring.xml"));
spring.xml in source file
BeanFactory bean = new XmlBeanFactory(new FileSystemResource("src/spring.xml"));
this is another code to load beans.xml file
ApplicationContext context = new GenericXmlApplicationContext("beans.xml");
my question is that is there any standards or conventions for creation of xml file name and location of file in real project.because in some reading articles i also found that there might be multiple xml files for large project like service.xml and dao.xml.
It can be useful to have bean definitions span multiple XML files. Often each individual XML configuration file represents a logical layer such as defining DAO beans etc. in your architecture but you should always place your XML configuration files under src/resources and access them as
new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});
From the Spring's Manual:
You can use the application context constructor to load bean definitions from all these XML fragments. This constructor takes multiple Resource locations, as was shown in the previous section. Alternatively, use one or more occurrences of the element to load bean definitions from another file or files. For example:
<beans>
<import resource="services.xml"/>
<import resource="resources/messageSource.xml"/>
<import resource="/resources/themeSource.xml"/>
</beans>
I am creating an application which uses Spring beans and I need to initialize ApplicationContext from xml. As it is not a server application, it doesn't have WEB-INF folder.So, where I should put the xml file?
Use ClassPathXmlApplicationContext:
ApplicationContext ctx =
new ClassPathXmlApplicationContext("applicationContext.xml");
Or consider migrating to #Configuration:
ApplicationContext ctx =
new AnnotationConfigApplicationContext(AppConfig.class);
where AppConfig is annotated with #Configuration and no XML is needed.
The spring documentation for this topic is a little overwhelming at first. A handy starting point in the spring documentation for application context config is here
A file system xml application context is probably the easiest to start with. So:
ApplicationContext appCtx =
new FileSystemXmlApplicationContext("/path/to/springconfig.xml");
Use ClassPathApplicationContext if you have the xml configuration in your application class path. In this example it might be a springconfig.xml under a project directory src/config/springconfig.xml.
ApplicationContext appCtx =
new ClassPathXmlApplicationContext("config/springconfig.xml");
If you are unsure where your springconfig.xml ends up after you have built your application, you can use the following command to list the contents of your jar:
jar -tvf myapp.jar
For a default eclipse java project, the project-home/bin directory is the start of the classpath.
A related question was asked here
Check this example Spring Setter Injection
If the XML is in the applications classpath then use like this
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Otherwise if the XML is in File system then use
ApplicationContext context = new FileSystemXmlApplicationContext("beans.xml");