- Creating Spring Application Context Using XML
- Creating a Spring Application Context from Multiple Files
- How to add context.xml file to embedded tomcat server in Java?
- Method 1: Use the Tomcat Embedded API
- Method 2: Use a Tomcat Context Descriptor
- Method 3: Use a Tomcat Context Config
- Method 4: Use a Tomcat ContextConfig
Creating Spring Application Context Using XML
Spring application contexts can be bootstrapped in any environment, including JUnit tests, web application, even standalone application.
Here a sample to load application context in «common» standalone Java application:
public static void main(String[] args) < ApplicationContext appContext = new ClassPathXmlApplicationContext( "com/dariawan/bankofjakarta/spring-config.xml"); TxService txService = appContext.getBean("txService", TxService.class); try < txService.transferFunds(new BigDecimal("200"), "Transfer 200", "5008", "5007"); >catch (InvalidParameterException|AccountNotFoundException| InsufficientFundsException|InsufficientCreditException ex) < System.out.println("Exception: " + ex.getMessage()); >>
And here another example using an application context inside a JUnit System Test:
package com.dariawan.bankofjakarta.service.impl; import com.dariawan.bankofjakarta.domain.Account; import com.dariawan.bankofjakarta.exception.AccountNotFoundException; import com.dariawan.bankofjakarta.exception.InsufficientCreditException; import com.dariawan.bankofjakarta.exception.InsufficientFundsException; import com.dariawan.bankofjakarta.exception.InvalidParameterException; import com.dariawan.bankofjakarta.service.AccountService; import com.dariawan.bankofjakarta.service.TxService; import java.math.BigDecimal; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TxServiceTest < protected TxService txService; protected AccountService accountService; @Before public void setUp() < // Create the application from the configuration ApplicationContext context = new ClassPathXmlApplicationContext( "com/dariawan/bankofjakarta/**/spring-config-test.xml"); // Look up the application service interface txService = context.getBean("txService", TxService.class); accountService = context.getBean("accountService", AccountService.class); >private Account getAccount(String accountId) < try < return accountService.getDetails(accountId); >catch (InvalidParameterException ex) < return null; >catch (AccountNotFoundException ex) < return null; >> @Test public void testTransferFunds() throws InvalidParameterException, AccountNotFoundException, InsufficientCreditException, InsufficientFundsException < Account accFrom1 = getAccount("5008"); BigDecimal balanceFromNow = accFrom1.getBalance(); Account accTo1 = getAccount("5007"); BigDecimal balanceToNow = accTo1.getBalance(); txService.transferFunds(new BigDecimal("200"), "Transfer 200", accFrom1.getAccountId(), accTo1.getAccountId()); Account accFrom2 = getAccount("5008"); assertEquals(accFrom2.getBalance().toString(), (balanceFromNow.subtract(new BigDecimal("200"))).toString()); Account accTo2 = getAccount("5007"); // because credit account - subtract assertEquals(accTo2.getBalance().toString(), (balanceToNow.subtract(new BigDecimal("200"))).toString()); >>
We can load bean definitions is from files which located in:
And it’s also possible to load from multiple files.
Creating a Spring Application Context from Multiple Files
A Spring application context can be configured from multiple files. We can partition (grouping) bean definitions into logical groups. The best practice is to separate out application beans from infrastructure beans. This is because infrastructure often changes between environments.
Let’s check spring configuration in Bank of Jakarta example application. So far, it’s a mixed configuration in one file:
Now, we partition above configuration into separated files:
- spring-tx-config.xml: infrastructure beans, handling database connection and transaction manager
- spring-dao-config.xml: application beans, handling DAOs configuration
- spring-service-config.xml: application beans, handling Services configuration
- spring-aop-config.xml: application beans, AOP and point-cuts
- spring-config.xml: main configuration, imports for the other four xml.
How to add context.xml file to embedded tomcat server in Java?
When using an embedded Tomcat server in a Java application, it may be necessary to add a context.xml file to configure the server’s behavior. This file is typically used to specify resources such as data sources that should be made available to the application. However, adding a context.xml file to an embedded Tomcat server can be a bit tricky and may require some additional setup.
Method 1: Use the Tomcat Embedded API
To add a context.xml file to an embedded Tomcat server using the Tomcat Embedded API, you can follow these steps:
Tomcat tomcat = new Tomcat();
File baseDir = new File("path/to/base/dir"); tomcat.setBaseDir(baseDir.getAbsolutePath());
Context context = tomcat.addContext("/myapp", baseDir.getAbsolutePath());
File configFile = new File("path/to/context.xml"); context.setConfigFile(configFile.toURI().toURL());
File webAppDir = new File("path/to/webapp"); tomcat.addWebapp(context, "", webAppDir.getAbsolutePath());
Here is the complete code:
Tomcat tomcat = new Tomcat(); File baseDir = new File("path/to/base/dir"); tomcat.setBaseDir(baseDir.getAbsolutePath()); Context context = tomcat.addContext("/myapp", baseDir.getAbsolutePath()); File configFile = new File("path/to/context.xml"); context.setConfigFile(configFile.toURI().toURL()); File webAppDir = new File("path/to/webapp"); tomcat.addWebapp(context, "", webAppDir.getAbsolutePath()); tomcat.start();
I hope this helps you add a context.xml file to your embedded Tomcat server using the Tomcat Embedded API.
Method 2: Use a Tomcat Context Descriptor
To add a context.xml file to an embedded Tomcat server using a Tomcat Context Descriptor, follow these steps:
Context> Resource name="jdbc/myDataSource" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="myuser" password="mypassword" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/mydatabase"/> Context>
- Create a META-INF directory inside your project’s src/main/resources directory.
- Inside the META-INF directory, create a file named context.xml and copy the contents of the context.xml file created in step 1.
- In your Java code, add the following lines to create a Context object and set its configuration using the ContextConfig class:
Context context = tomcat.addContext("", new File(".").getAbsolutePath()); ContextConfig contextConfig = new ContextConfig(); context.addLifecycleListener(contextConfig); contextConfig.setDefaultWebXml(new File("src/main/webapp/WEB-INF/web.xml").getAbsolutePath()); contextConfig.setContextXml(new File("src/main/resources/META-INF/context.xml").getAbsolutePath());
- Finally, add any necessary resources or servlets to your context.xml file and deploy your application to the embedded Tomcat server.
Note: In this example, we assume that the web.xml file is located in the src/main/webapp/WEB-INF directory. Adjust the path accordingly if your web.xml file is located elsewhere.
That’s it! With these steps, you should be able to add a context.xml file to your embedded Tomcat server using a Tomcat Context Descriptor.
Method 3: Use a Tomcat Context Config
To add a context.xml file to an embedded Tomcat server using a Tomcat Context Config, you can follow these steps:
Context context = new Context(); context.setPath("/myapp"); context.setDocBase("/path/to/myapp");
Tomcat tomcat = new Tomcat(); tomcat.getHost().addChild(context);
ContextConfig contextConfig = new ContextConfig(); context.addLifecycleListener(contextConfig);
contextConfig.setDefaultWebXml("/path/to/context.xml");
tomcat.start(); tomcat.getServer().await();
Here’s the complete example code:
import org.apache.catalina.Context; import org.apache.catalina.startup.ContextConfig; import org.apache.catalina.startup.Tomcat; public class EmbeddedTomcatExample public static void main(String[] args) throws Exception Context context = new Context(); context.setPath("/myapp"); context.setDocBase("/path/to/myapp"); Tomcat tomcat = new Tomcat(); tomcat.getHost().addChild(context); ContextConfig contextConfig = new ContextConfig(); context.addLifecycleListener(contextConfig); contextConfig.setDefaultWebXml("/path/to/context.xml"); tomcat.start(); tomcat.getServer().await(); > >
This code creates a Tomcat server with a context at /myapp that points to /path/to/myapp , and sets the location of the context.xml file to /path/to/context.xml .
Method 4: Use a Tomcat ContextConfig
To add a context.xml file to an embedded Tomcat server using a Tomcat ContextConfig, follow these steps:
Tomcat tomcat = new Tomcat(); tomcat.setPort(8080);
Context context = tomcat.addContext("/myapp", new File(".").getAbsolutePath());
ContextConfig contextConfig = new ContextConfig(); context.addLifecycleListener(contextConfig);
contextConfig.setDefaultWebXml(new File("conf/context.xml").getAbsolutePath());
tomcat.start(); tomcat.getServer().await();
import java.io.File; import org.apache.catalina.Context; import org.apache.catalina.startup.ContextConfig; import org.apache.catalina.startup.Tomcat; public class Main public static void main(String[] args) throws Exception Tomcat tomcat = new Tomcat(); tomcat.setPort(8080); Context context = tomcat.addContext("/myapp", new File(".").getAbsolutePath()); ContextConfig contextConfig = new ContextConfig(); context.addLifecycleListener(contextConfig); contextConfig.setDefaultWebXml(new File("conf/context.xml").getAbsolutePath()); tomcat.start(); tomcat.getServer().await(); > >
This code creates a new Tomcat instance and sets its port to 8080. It then creates a new context with the path «/myapp» and sets its base directory to the current directory. A new ContextConfig is created and added to the context as a LifecycleListener. The location of the context.xml file is set to «conf/context.xml». Finally, the Tomcat server is started and the program waits for the server to shut down.
This method of adding a context.xml file to an embedded Tomcat server is useful when you need to configure a context with a specific set of parameters or when you want to use a custom context.xml file.