Java Reference
In-Depth Information
public void checkout(ShoppingCart cart) throws IOException {
double total = 0;
for (Product product : cart.getItems()) {
total += product.getPrice();
writer.write(new Date() + "\t" + total + "\r\n");
public void closeFile() throws IOException {
In the Cashier class, the openFile() method opens the text file with the cashier name as the file
name in the specified system path. Each time you call the checkout() method, a checkout record will be
appended to the text file. Finally, the closeFile() method closes the file to release its system resources.
Then you declare a cashier bean with the name cashier1 in the IoC container. This cashier's
checkout records will be recorded in the file c:/cashier/cashier1.txt . You should create this directory
in advance or specify another existing directory. (On a Unix derivative, you might put it in your home
directory: ~/cashier .)
<beans ...>
<bean id="cashier1" class="">
<property name="name" value="cashier1" />
<property name="path" value="c:/cashier" />
However, in the Main class, if you try to check out a shopping cart with this cashier, it will result in a
NullPointerException . The reason for this exception is that no one has called the openFile() method for
initialization beforehand.
import org.springframework.context.ApplicationContext;
public class Main {
public static void main(String[] args) throws Exception {
// checkout() throws an Exception
ApplicationContext context =
new FileSystemXmlApplicationContext("beans.xml");
Cashier cashier1 = (Cashier) context.getBean("cashier1");
Search WWH ::

Custom Search