一 .注解:
1.@Autowire和@Resource的区别
@Autowired与@Resource都可以用来装配bean. 都可以写在字段上,或写在setter方法上。
@Autowired默认按类型装配(属于spring规范),默认情况下必须要求依赖对象必须存在,如果要允许null 值,可以设置它的required属性为false,如:@Autowired(required=false) ,如果我们想使用名称装配可以结合@Qualifier注解进行使用,@Qualifier(value = “cat2”)
@Nullable 允许属性为空(找不到可以注入的bean不会报错)
@Resource(属于J2EE复返),默认按照名称进行装配,名称可以通过name属性进行指定。如果没有指定name属性,当注解写在字段上时,默认取字段名进行按照名称查找,如果注解写在setter方法上默认取属性名进行装配。 当找不到与名称匹配的bean时才按照类型进行装配。但是
需要注意的是,如果name属性一旦指定,就只会按照名称进行装配
总结:它们的作用相同都是用注解方式注入对象,但执行顺序不同。@Autowired先byType,@Resource先byName。
2.扫描注解
@Component (类注解)别名(@Service,@Repository,@Controller)
3.java配置config配置
1)配置类注解 @Configuration @ComponentScan("com.project.model") @Import(SpringConfig01.class)
2)配置类中添加bean @Bean
5.aop注释
@Aspectj(切面类)
@Before("execution(* com.project.*.*(..))") @After @AfterRunning @AfterThrowing @Around(切面方法)
AspectJ 切面注解中五种通知注解:@Before、@After、@AfterRunning、@AfterThrowing、@Around_苍鹰蛟龙的博客-CSDN博客_@after
二.xml配置头
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> <context:annotation-config/><!--开启注解--> <aop:aspectj-autoproxy/><!--开启aop注解--> <context:component-scan base-package="com.project"/><!--spring扫描注解-->
<bean id="log" class="com.lida.AspectLog"/> <!--aop常用方式--> <aop:config> <aop:aspect ref="log"> <aop:pointcut id="all" expression="execution(* com.project.*.*(..))"/> <aop:after method="after" pointcut-ref="all"/> <aop:before method="before" pointcut-ref="all"/> </aop:aspect> </aop:config> <!--aop常用方式--> </beans>
三.p注解,c注解
xmlns:p="http://www.springframework.org/schema/p"
<bean id="man" class="com.project.model.Man" p:sex="我是男人"/>
需要setter方法
xmlns:c="http://www.springframework.org/schema/c"
bean id="woman" class="com.project.model.Women" c:sex="我是女人"/>
需要构造函数
四.使用spring的方式
1.使用xml配置
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("services.xml"); PeopleService ps =applicationContext.getBean("peopleService",PeopleService.class);
2使用java配置(关联 一.3)
ApplicationContext context = new AnnotationConfigApplicationContext(myConfig.class);
User getUser = applicationContext.getBean("getUser", User.class);