// 早期的方式创建资源
Resource res=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(res); Printer
printer=factory.getBean("printer",Printer.class);
printer.print("答应测试");
如果使用国际化标签必须在XML中配置
mess //国际标签的名字,可以配写多个
applicationContext.xml
2222.0
测试代码(如果在XML文件中有两个Printer.Class必须指定唯一name的Printer printer = context.getBean("printer",Printer.class) printer)
ApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml"); // Printer printer=context.getBean(Printer.class); // 两个bean在applicationContext.xml /** ** */ //Printer printer = context.getBean(Printer.class);//会报错,必须指定唯一的 Printer printer = context.getBean("printer",Printer.class); printer.print("答应测试");
声明多个XML文件bean.xml
mess
测试代码bean.xml与applicationContext.xml里面的bean-name不能为一样
ref里的bean名称与name相等,property的name为类中的名称
ApplicationContext ctx=new ClassPathXmlApplicationContext(new String[]{"bean.xml","applicationContext.xml"});
Printer printer=ctx.getBean("printer",Printer.class);
Printer printer1=ctx.getBean("printer1",Printer.class);
printer1.print("aaa");
printer.print("datiny");
mess.properties
hello=welcome,{0}
now=now is\:{0}测试代码
//国际化 参数1配置文件key 参数2占位符参数 参数3语言环境locale
ApplicationContext ctx=new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml","bean.xml"});
String hello=ctx.getMessage("hello",new Object[]{"spring"},Locale.getDefault());
System.out.println(hello);
String hello1=ctx.getMessage("now",new Object[]{new Date()},Locale.getDefault());
System.out.println(hello1);
事件必须在XML文件配置
EmailEvent.java
package bean;
import org.springframework.context.ApplicationEvent;
public class EmailEvent extends ApplicationEvent{
private static final long serialVersionUID = 1L;
private String address;
private String text;
//source事件源
public EmailEvent(Object source) {
super(source);
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public EmailEvent(Object source, String address, String text) {
super(source);
this.address = address;
this.text = text;
}
}
EmailListener.java
package bean; import org.springframework.context.ApplicationListener; //监听器 public class EmailListener implements ApplicationListener{ @Override public void onApplicationEvent(EmailEvent arg0) { System.out.println(arg0.getAddress()); System.out.println(arg0.getText()); System.out.println(arg0.getSource()); System.out.println(arg0.getTimestamp()); } }
/* * 手动抛事件 */ //先绑定事件 ApplicationContext ctx=new ClassPathXmlApplicationCo