HelloImpl.java
package shuai.spring.study;
public class HelloImpl implements HelloApi {
@Override
public void sayHello() {
System.out.println("Hello World!");
}
}
HelloImpl5.java
package shuai.spring.study;
public class HelloImpl5 implements HelloApi {
private HelloApi helloApi;
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public HelloApi getHelloApi() {
return helloApi;
}
public void setHelloApi(HelloApi helloApi) {
this.helloApi = helloApi;
}
@Override
public void sayHello() {
System.out.println("==========装饰一下===========");
System.out.println(message);
helloApi.sayHello();
System.out.println("==========装饰一下===========");
}
}
测试类
package shuai.spring.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import shuai.spring.study.HelloApi;
public class HelloTest {
@Test
public void testHelloWorld() {
@SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext("HelloWorld.xml");
HelloApi helloApi = context.getBean("hello", HelloApi.class);
helloApi.sayHello();
}
}
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="hello1" class="shuai.spring.study.HelloImpl"/>
<bean id="hello" class="shuai.spring.study.HelloImpl5" p:message="Hello p" p:helloApi-ref="hello1"/>
</beans>
注意,使用p要先指定p命名空间:xmlns:p="http://www.springframework.org/schema/p"
测试输出结果:
==========装饰一下===========
Hello p
Hello World!
==========装饰一下===========
就两种形式
普通属性,p:属性="值"
如果引用bean,就p:属性-ref="bean的id"(bean的name什么的都可以,就是标识)