使用注解定义Bean
@Component("car") public class Car { @Value("Red") private String color; public String getColor() { return color; } public void setColor(String color) { this.color = color; } }
使用value可以给变量赋值 而@Compontent相当于xml中<bean id ="car" class="dao.cn.Car"/>
使用注解实现Bean组件装配
spring提供了@Autowired注解实现Bean的装配
@Component("stu") public class Student { @Value("高尚的动物世界") private String name; @Value("19") private Integer age; // @Resource(name = "car") jdk 自己的注解 @Autowired //Spring 的注解 @Qualifier(value = "car") private Car car; public Car getCar() { return car; } public void setCar(Car car) { this.car = car; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
当然JDK也提供了一种注解@Resource
静态代理
静态代理不需要实现任何接口
定义subject接口
public interface Subject { public void request(); }
然后定义RealSubject类实现subject接口
public class RealSubject implements Subject { public void request() { System.out.println("这是真实对象"); } }
再然后定义ProxySubject类,同样也实现Subject接口
public class ProxySubject implements Subject { private RealSubject realSubject = new RealSubject(); public void request() { System.out.println("之前"); realSubject.request(); System.out.println("之后"); } }