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");
Related
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 :
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.
Here i have a bean initialized InitializingBean in Spring MVC application. In order to register in spring-servlet application context, i two lines of code below:
#Autowired
private ApplicationContext context;
#Override
public void afterPropertiesSet() throws Exception {
if (context.getParent() != null) { // debug mode and add a breakpoint here, four times came here while application start up
}
}
Obviously, if four root application context initialized, some where error. but i really don't know why?
Here i make some assumption:
contextConfigLocation in web.xml file is classpath*:, and tomcat may detect multiple applicationContext.xml files under classpath jar files.(but spring xml files are really not locate in such jar files)
there are some configuration class in jar files and who make spring mvc application scan the same jar file twice or more(but i did not find such class)
Maybe i'm totally error, hope someone can give me some hint and thanks.
when starting your tomcat,the tags in your web.xml ,specificly,your codes will detect the configuration you wrote,initilized the spring container,such as,Application-Context.xml,if there is any tag in this file , the Spring will add the file you write, for example, you write "Application-context-data.xml" in your tag,the Spring container will initilized it !
I have a Spring application that at startup needs to read some basic properties from a file but nothing sensitive (timeout values, directory locations, etc.). It needs to be edited before starting the application depending on the desired target server.
My first easy idea was to place the file under home target server, then load it into Spring
<context:property-placeholder location="file:${JBOSS_HOME}/standalone/config/application.properties" />.
I found other sources mentioning the usage of System properties or JBoss modules.
Are there any advantages/disadvantages for using one on another? What else should I consider when choosing the appropriate one in my case?
In my understanding Spring looks by default properties file in your app directory, or you can register a properties file with XML config or Java config (Annotations):
<context:property-placeholder location="classpath*:my.properties"/>
Then you refer to the properties in your beans:
#Component
class MyClass {
#Value("${my.property.name}")
private String[] myValues;
}
or
#Configuration
#PropertySource("classpath:/com/myco/app.properties")
public class AppConfig {
#Autowired
Environment env;
#Bean
public TestBean testBean() {
TestBean testBean = new TestBean();
testBean.setName(env.getProperty("testbean.name"));
return testBean;
}
}
the properties file can be updated at any time (just stoping serv) in the apps server, tomcat, jboss, etc.
note sure if that's what you want,
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>