Recently, I looked at the source code of pluto, and finally understood a small method of how multiple applications share information. Then write a small demo
First write a jar package with only two classes in the package, a singleton and a Person bean
public class MySingleClass { private static MySingleClass instance; public Person person; public MySingleClass(Person p){ instance = this; person = p; } public static MySingleClass getInstance(){ return instance; } } public class Person { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
After writing, maven is packaged into a jar package, and then placed in the lib directory of tomcat.
Then write two projects, each with only one class for simple testing, and then it is very important that both maven projects depend on the above jar, but the scope is set to provided, which is only referenced at compile time.
This class in project 1 generates a singleton for MySingleClass with the newly created Person object as a parameter after the servlet container is started.
public class MyServlet implements ServletContextListener{ @Override public void contextInitialized(ServletContextEvent sce) { // TODO Auto-generated method stub Timer time = new Timer (); time.schedule(new TimerTask() { @Override public void run() { // TODO Auto-generated method stub Person person =new Person(); person.setName("mao"); new MySingleClass(person); } }, 10000); } }
In project 2, the Person.name property of the MySingleClass singleton is read.
public class MyServlet implements ServletContextListener{ public void contextInitialized(ServletContextEvent sce) { // TODO Auto-generated method stub Timer timer = new Timer (); timer.schedule(new TimerTask() { @Override public void run() { // TODO Auto-generated method stub if(MySingleClass.getInstance() == null){ System.out.println("no name"); }else { System.out.println(MySingleClass.getInstance().person.getName()); } } }, 10,1000); } }
Of course can not forget to register listeners in their respective web.xml. Deploying two projects to the same tomcat startup results in printing mao after printing a few no names.
Why is this so? Because project 1 loads MySingleClass in tomcat's lib directory into memory, project 2 will not reload it, so their static properties refer to the same object, that is, the newly created MySingleClass instance in project 1.