Spring 注解驱动开发
容器(Container)
配置类 == 配置文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| @Configuration
@ComponentScan(value="com.atguigu", excludeFilters = { @Filter(type="FilterType.ANNOTATION",classes={Controller.class}) })
@Filter(type="FilterType.ASSIGNABLE_TYPE",classes={BookService.class})
@Filter(type=FilterType.CUSTOM, classes={MyTypeFilter.class})
@ComponentScan(value="com.atguigu", includeFilters = { @Filter(type="FilterType.ANNOTATION",classes={Controller.class})},useDefaultFilters = false)
@ComponentScans( value = { @ComponentScan(value="com.atguigu", includeFilters = { @Filter(type="FilterType.ANNOTATION",classes={Controller.class})},useDefaultFilters = false) } ) public class MainConfig{ @Bean("person") public Person person(){ return new Person("lisi",20); } }
|
MyTypeFilter.java 自定义Filter的实现类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public class MyTypeFilter implements TypeFilter{ @Override public boolean math(MetadataReader metadataReader, MetaDataReaderFactory metadatareaderfactory) { AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata(); ClassMetadata classMetadata = metadataReader.getClassMetadata(); Resource resource = metadataReader.getResource(); return false; } }
|
使用@Scope调整作用域
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| @Configuration
@Conditional({WindowsCondition.class}) @Import({Color.class, Red.class, MyImportSelector.class, MyImportBeanDefinitionRegistrar}) public class MainConfig2{
@Scope("prototype"/"singleton") @Lazy @Bean("person") public Person person() { return new Person("zhangsan",25); }
@Conditional({WindowsCondition.class}) @Bean("bill") public Person person01(){ return new Person("Bill Gates",62); } @Conditional({LinuxCondition.class}) @Bean("linus") public Person person02(){ return new Person("linus", 48); }
@Bean public ColorFactoryBean colorFactoryBean(){ return new ColorFactoryBean(); } }
|
Color
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public class Color{ } public class Red{ } public class Blue{ } public class Yellow{ } public class RainBow{ }
|
MyImportSelector.java
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class MyImportSelector implements ImportSelector{ @Override public String[] selectImports(AnnotationMetadata importingClassMetadata){ return new String[]{"com.bean.Blue", "com.bean.Yellow"}; } }
|
LinuxCondition.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| public class LinuxCondition implements Condition {
@Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); ClassLoader classLoader = context.getClassLoader(); Environment environment = context.getEnvironment(); BeanDefinitionRegistry registry = context.getregistry(); boolean definition = registry.containsBeanDefinition("person"); String property = environment.getProperty("os.name"); if(property.contains("Linux")) { return true; } return false; } }
|
MyImportBeanDefinitionRegistrar.java –> 手工注册
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar{
@Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { boolean definition = registry.containsBeanDefinition("Red->要写全类名"); boolean definition2 = registry.containsBeanDefinition("Blue->要写全类名"); if(definition && definition2) { RootBeanDefinition beanDefinition new RootBeanDefinition(Rainbow.class); registry.registerBeanDefinitions("rainBow",beanDefinition); } } }
|
ColorFactoryBean
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| public class ColorFactoryBean implements FactoryBean<Color>{ @Override public Color getObject() thorws Exception{ return new Color(); } @Override public Class<?> getObjectType() { return Color.class } @Override public boolean isSingleton(){ return false; } }
|
WindowsCondition
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public class WindowsCondition implements Condition {
@Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { Environment environment = context.getEnvironment(); String property = environment.getProperty("os.name"); if(property.contains("Windows")) { return true; } return false; } }
|
配置文件
1 2 3 4 5 6 7 8 9 10 11 12 13
|
<context:component-scan base-package="com.atguigu" use-default-filters="false"></context:component-scan> <context:property-placeholder location="classpath:person.properties"/>
<bean id="person" class="com.bean.Person" scope="singleton" init-method="" destroy-method=""> <property name="age" value="18"></property> <property name="name" value="zhangsan"></property> </bean>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
|
BookController.java
1 2 3 4 5
| @Controller public class BookController{ @AutoWired(required=false) private BookService bookService; }
|
BookService.java
1 2 3 4 5
| @Service public class BookService{ @AutoWired private BookDao bookDao; }
|
BookDao.java
1 2 3 4
| @Repository public class BookDao{ }
|
Main 函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public class MainTest{ public static void main(String... args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml"); Person bean = (Person) applicationContext.getBean("person"); System.out.println(bean); AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class); Person bean = applicationContext.getBean("person"); System.out.println(bean); String[] namesForType = applicationContext.getBeanNamesForType(Person.class); for(String string : namesForType) { System.out.println(string); } } }
|
IOCTest.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| public class IOCTest{ @Test public void test01(){ AnnotationConfigapplicationContext applicationContext new AnnotationConfigapplicationContext(MainConfig.class); String[] definitionNames applicationContext.getBeanDefinitionName(); for(String name : definitionNames) { System.out.println(name); }
} public void test02(){ AnnotationConfigapplicationContext applicationContext new AnnotationConfigapplicationContext(MainConfig2.class); String[] definitionNames applicationContext.getBeanDefinitionName(); for(String name : definitionNames) { System.out.println(name); } Object bean = applicationContext.getBean("person"); Object bean2 = applicationContext.getBean("person"); } public void test03(){ AnnotationConfigapplicationContext applicationContext new AnnotationConfigapplicationContext(MainConfig2.class); ConfigurableEnvironment environment = applicationContext.getEnvironment(); environment.getProperty("os.name"); System.out.println(property); String[] definitionNames applicationContext.getBeanNamesForType(Person.class); for(String name : definitionNames) { System.out.println(name); } Map<String, Person> persons = applicationContext.getBeansOfType(Person.class); System.out.println(persons); } @Test public void testImport(){ AnnotationConfigapplicationContext applicationContext new AnnotationConfigapplicationContext(MainConfig2.class); String[] definitionNames applicationContext.getBeanDefinitionName(); for(String name : definitionNames) { System.out.println(name); } Blue bean = applicationContext.getBean(Blue.class); System.out.println(bean); Object bean2 = applicationContext.getBean("colorFactoryBean"); System.out.println("bean的类型" + bean2.getClass()); Object bean3 = applicationContext.getBean("&colorFactoryBean"); System.out.println("bean的类型" + bean3.getClass()); } }
|
Bean的生命周期
MainConfigOfLifeCycle.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
@Configuration @ComponentScan("com.bean") public class MainConfigOfLifeCycle{ @bean(initMethod="init",destroyMethod="destroy") public Car car(){ return new Car(); } }
|
MyBeanPostProcessor.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
@Component public class MyBeanPostProcessor implements BeanPostProcessor{ @Override public Object postProcessBeforeInitialization(Object bean,String beanName) throws BeanException{ System.out.println(beanName + "=>" + bean); return bean; } @Override public Object postProcessAfterInitilization(Object bean,String beanName) throws BeanException{ System.out.println(beanName + "=>" + bean); return bean; } }
|
Car.java
1 2 3 4 5 6 7 8 9 10 11
| public class Car{ public Car(){ System.out.println("car constructor"); } public init(){ System.out.println("car init..."); } public destroy(){ System.out.println("car destroy..."); } }
|
Cat.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| @Component public class Cat implements InitilizingBean, DisposableBean{ public Cat(){ System.out.println("cat instructor"); } @Override public void destroy() throws Exception{ System.out.println("cat... destroy..."); } @Override public void afterPropertiesSet() throws Exception{ System.out.println("Cat... afterPropertiesSet..."); } }
|
Dog.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| @Component public class Dog implements ApplicationContextAware{ private ApplicationContext applicationContext; public Dog(){ System.out.println("dog constructor"); } @PostConstruct public void init(){ System.out.println("dog @PostConstruct..."); } @PreDestroy public void destroy(){ System.out.println("dog @PostDestroy"); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeanException{ this.applicationContext = applicationContext; } }
|
IOCTest_LifeCycle.java
1 2 3 4 5 6 7 8 9 10 11
| public class IOCTest_LifeCycle{ @Test public void test01(){ AnnotationConfigapplicationContext applicationContext new AnnotationConfigapplicationContext(MainConfigOfLifeCycle.class); System.out.println("容器创建完成"); applicationContext.close(); } }
|
属性赋值
MainConfigOfPropertyValues.java
1 2 3 4 5 6 7 8 9
| @Configuration
@PropertySource(value={"classpath:/person.properties"}) public class MainConfigOfPropertyValues{ @Bean public Person person(){ } }
|
Person.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class Person{ @Value("zhangsan") private String name; @Value("#{20-2}") private Integer age; @Value("${person.nickName}") private String NickName; }
|
person.properties
IOCTest_LifeCycle.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public class IOCTest_PropertyValue{ @Test public void test01(){ AnnotationConfigapplicationContext applicationContext new AnnotationConfigapplicationContext(MainConfigOfPropertyValues.class); System.out.println("容器创建完成"); Person person = (Person)applicationContext.getBean("person"); ConfigurableEnvironment environment = applicationContext.getEnvironment(); String property = environment.getProperty("person.nickName"); System.out.println(property); String[] definitionNames applicationContext.getBeanDefinitionName(); for(String name : definitionNames) { System.out.println(name); } applicationContext.close(); } }
|
自动装配
MainConfigAutowired.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
@Configuration @ComponentScan({"com.service","com.dao","com.controller"}) public class MainConfigAutowired{ }
|
Boss.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| @Component public class Boss{ private Car car; @Autowired public Boss(@Autowired Car car){ this.car = car; } public void setCar(Car car){ this.car = car; } }
|
IOCTest_Autowired.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class IOCTest_Autowired{ @Test public void test01(){ AnnotationConfigapplicationContext applicationContext new AnnotationConfigapplicationContext(MainConfigAutowired.class); System.out.println("容器创建完成"); BookService bookService = applicationContext.getBean(BookService.class); System.out.println(bookService); BookDao bookDao = applicationContext.getBean(BookDao.class); applicationContext.close(); } }
|
Profile
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
|
@Configuration @PropertySource("classpath:/dbconfig.proerties") public class MainConfigOfProfile implements EmbeddedValueResolverAware{ @Value("db.user") private String user; private StringValueResolver valueResolver; @Profile("dev") @Bean("devDataSource") public DataSource dataSourceDev(@Value(db.password) String pwd) { ComboPooledDataSource dataSource = new ComboPooledDataSource(); dataSource.setUser(user); dataSource.setPassword(password); dataSource.setJdbcUrc(valueResolverresolveStringValue("${db.driveClass}")); dataSource.setDriverClass("com.mysql.jdbc.Driver"); return null; } @Profile("test") @Bean("testDataSource") public DataSource dataSourceTest() { ComboPooledDataSource dataSource = new ComboPooledDataSource(); dataSource.setUser("root"); dataSource.setPassword("123456"); dataSource.setJdbcUrc("jdbc:mysql://localhost:3306/"); dataSource.setDriverClass("com.mysql.jdbc.Driver"); return null; } @Profile("prod") @Bean("prodDataSource") public DataSource dataSourceProd() { ComboPooledDataSource dataSource = new ComboPooledDataSource(); dataSource.setUser("root"); dataSource.setPassword("123456"); dataSource.setJdbcUrc("jdbc:mysql://localhost:3306/"); dataSource.setDriverClass("com.mysql.jdbc.Driver"); return null; } @Override public void setEmbeddedValueResolver(StringValueResolver resolver) { this.valueResolver = resolver; } }
|
dbconfig.proerties
1 2 3
| db.user = root db.password = 123456 db.driverClass = com.mysql.jdbc.Driver
|
MainConfigOfAOP.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
|
@Configuration @EnableAspectJAutoProxy public class MainConfigOfAOP{ @Bean public MathCalculator calculator(){ return new MathCalculator(); } @Bean public LogAspects logAspects() { return new LogAspects(); } }
|
MathCalculator
1 2 3 4 5 6
| public class MathCalculator{ public int div(int i, intj) { return i/j; } }
|
LogAspects.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| @Aspect public class LogAspects{ @PointCut("execution(public int com.aop.MathCalculator.*(..))") public void pointCut(){}; @Before("public int com.aop.MathCalculator.*(..)") public void logStart(JoinPoint joinPoint){ Object[] args = joinPoint.getArgs(); System.out.println(joinPoint.getSignator().getName()+"运行除法"+Arrays.asList(args)); } @After("pointCut()") public void logEnd(){ System.out.println("除法结束"); } public void logReturn(JointPoint joinPoint, Object result){ System.out.println("除法正常返回"+result); } @AfterThrowing(value="pointCut()", throwing="exception") public void logExpection(Exception exception){ System.out.println("除法异常信息") } }
|