1 DI
新建OrderService
package com.tes.service;
import com.spring.Component;
@Component("orderService")
public class OrderService {
}
新建Autowired 注解
package com.spring;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.FIELD})
public @interface Autowired {
}
添加Atuowired注解后需要spring来实现注入
怎么注入?
在创建bean时实现,通过getBean
2 Aware
spring中的Aware接口
创建BeanNameAware 接口
package com.spring;
public interface BeanNameAware {
void setBeanName(String name);
}
3 init
模拟初始化
创建InitializingBean接口
4 BeanPostProcessor
spring对bean初始化前后提供的一个拓展
新建BeanPostProcessor接口
package com.spring;
public interface BeanPostProcessor {
Object postProcessBeforeInitialization(Object bean, String beanName);
Object postProcessAfterInitialization(Object bean, String beanName);
}
实现
package com.tes.service;
import com.spring.BeanPostProcessor;
import com.spring.Component;
@Component
public class BeanPostProcessorImpl implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
if (beanName.equals("userService")){
System.out.println("初始化前");
((UserService)bean).setName("雷好呀");
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
System.out.println("初始化后");
return bean;
}
}
Test测试
|