this.admin = admin;
}
public Sharm getSharm() {
return sharm;
}
public void setSharm(Sharm sharm) {
this.sharm = sharm;
}
public Nola getNola() {
return nola;
}
public void setNola(Nola nola) {
this.nola = nola;
}
public String getAdmin() {
return admin;
}
public void setAdmin(String admin) {
this.admin = admin;
}
}
3)编写 Spring 配置文件
<?xml version="1.0" encoding="UTF-8"?><beans xmlns=“http://www.springframework.org/schema/beans”
xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
4)测试
public class AutowireTest {
@Test
public void test(){
// 固定写法
ApplicationContext context = new ClassPathXmlApplicationContext(“autowire.xml”);
// 得到对象,其中参数为对象名
Lab lab = context.getBean(“lab”, Lab.class);
// 开始使用对应同学类的方法
lab.sharm.show();
lab.nola.show();
}
}
两种自动装配的属性:
| 属性名 | 作用 |
| — | — |
| byName | 按照属性名自动装配,使用该属性后,会自动在容器上下文中查找和自己对象 setter 方法后面的值相同的 bean id。如果有,就取出注入,如果没有,就报(NullPointerException)空指针异常。 |
| byType | 按照类型自动装配,使用该属性后,会自动在容器上下文中查找和自己对象类型相同的 bean。同时,在 Spring 容器中,同一类型的对象必须要唯一。 |
2.2.1 byName
保持三个实体类不变,修改 Spring 配置文件如下:
2.2.2 byType
===============================================================================
| 注释名 | 配置 | 位置 | 作用 |
| — | — | — | — |
| @Autowired | 需要加入配置文件以及导入 jar 包 | 可以写在字段上,或写在setter方法上 | 根据类型自动装配的,如果想使用 byName 装配,则需要另外加上 @Qualifier 注解 |
| @Resource | 不需要加入配置文件,需要导入 jar 包 | 可以写在字段上,或写在setter方法上 | 优先使用指定的name属性进行装配,其次使用 byName 装配,最后使用 byType 装配,如果都不成功,则报异常 |
1)导入 spring-aop 包
2)修改 Spring 配置文件
<?xml version="1.0" encoding="UTF-8"?><beans xmlns=“http://www.springframework.org/schema/beans”
xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
修改成如下:
<?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
https://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/
小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数初中级Java工程师,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年最新Java开发全套学习资料》送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频
如果你觉得这些内容对你有帮助,可以添加下面V无偿领取!(备注Java)
学习资料》送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。**
[外链图片转存中…(img-i3Yea45m-1710891496658)]
[外链图片转存中…(img-sx3cEEdW-1710891496659)]
[外链图片转存中…(img-ZDlIYrxs-1710891496659)]
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频
如果你觉得这些内容对你有帮助,可以添加下面V无偿领取!(备注Java)
[外链图片转存中…(img-oHiqxHDK-1710891496660)]