基于:【狂神说Java】Spring5最新完整教程IDEA版通俗易懂
目录
1 autowire
<bean id="user" class="xyz.cqulwj.pojo.User" autowire="byName">
byName
寻找容器中id
和类中setName
方法中Name
一致的自动装配进去;byType
对象属性类型相同的自动装配(需要类型唯一);
2 注解自动装配
2.1 添加命名空间
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<bean id="address" class="xyz.cqulwj.pojo.Address"/>
<bean id="user" class="xyz.cqulwj.pojo.User"/>
</beans>
添加xmlns:context
,并显示配置config;只需要配置bean就行,在代码中进行注解自动装配;
2.2 @Autowired注解
public class User {
private String name;
@Autowired
private Address address;
}
当加载配置文件时,会调用二者的无参构造,然后自动装配address到User中,方式是byType,如果有两个类型一样,就按照名字匹配byName。可以使用@Qualifier(value = "xxx")
注解指定id
匹配;
2.3 @Resource注解
public class User {
private String name;
@Resource
private Address addr;
}
会先byName再byType。注意该注解在:import javax.annotation.Resource下;可以使用@Resource(name = “xxx”)来指定限定名;
3 自动装配bean
3.1 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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--注解支持-->
<context:annotation-config/>
<!--自动扫描包-->
<context:component-scan base-package="xyz.cqulwj.pojo"/>
</beans>
3.2 @Component
@Component
public class Address {}
自动装配bean,id
为小写的类名;可以在属性或者set方法上加上@Value
设置属性值;
3.3 一般规范
一般在程序开发中会把类进行分类,按照具体的逻辑分为:
- dao:使用
@Repository
- Service:使用
@Service
- controller:使用
@Controller
以上注解和@Component
作用一样都是装配bean产生对象。
3.4 生命周期@Scope
和xml配置一样,也可以通过scope设置对象的生命周期。
@Scope("singleton")
单例,仅有一个;@Scope("prototype")
原型,多个。
4 使用java配置Spring
4.1 创建配置文件
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import xyz.cqulwj.pojo.Address;
@Configuration
@ComponentScan("xyz.cqulwj.pojo")
public class MyConfig {
@Bean
public Address address(){
return new Address();
}
}
该文件的作用和.xml
是一样的,其中@Bean
的函数名就是id
。
4.2 获取ApplicationContext对象
public void annotationGetBeanTest(){
//获得上下文
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
//获得对象
Address address=context.getBean("address",Address.class);
//显示输出
logger.debug(address.toString());
}
使用.xml
配置需要使用ClassPathXmlApplicationContext("beans.xml")
来获取,但是使用了java配置,则需要使用AnnotationConfigApplicationContext(MyConfig.class)
来获取ApplicationContext
对象。