什么是注解及注解作用
1稿蹲、注解是代碼中特殊標(biāo)記,格式:@注解名稱(屬性名=屬性值鹊奖, 屬性名=屬性值 ..)
2苛聘、注解使用在類、方法忠聚、屬性
上
3设哗、作用:簡化xml的配置
常用注解
@Component
@Service
@Controller
@Repository
上述四個(gè)注解作用在類上-主要作用是實(shí)例化類
@AutoWired 根據(jù)屬性類型自動(dòng)注入
@Qualifier 根據(jù)屬性名稱進(jìn)行注入
@Resource 即可根據(jù)屬性類型注入 也可以根據(jù)屬性名稱進(jìn)行注入 javax 擴(kuò)展包 提供的
上述三個(gè)注解作用是注入屬性
@value 屬性賦值
部分代碼如下
目標(biāo):
為PersonEntity注入name及sex值,并將PersonEntity注入到PersonServiceImpl類中两蟀,然后調(diào)用PersonEntity中的add()方法网梢,輸出注入的屬性值
1、新建PersonEntity類及PersonServiceImpl類
// 這四個(gè)注解都可以使用
// @Repository()
// @Service
// @controller
// @Repository
@Component
public class PersonEntity {
@Value("張三")
private String name;
@Value("男")
private String sex;
public void add () {
System.out.println("執(zhí)行了PersonEntity赂毯,姓名:" + name + "性別:" + sex);
}
}
@Service
public class PersonServiceImpl {
@Autowired
private PersonEntity personEntity;
public void getPersonEntity() {
System.out.println("執(zhí)行PersonServiceImpl.......");
personEntity.add();
}
}
2战虏、bean.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:content="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 https://www.springframework.org/schema/context/spring-context.xsd">
<!--
開啟注解
base-package:需要掃描類的路徑 可以是多個(gè)用逗號(hào)隔開base-package="work.chenc.entity,base-package="work.chenc.service""
ase-package="work.chenc.*" * 通配符 表示掃描work.chenc 包下面所有帶有注解的類
-->
<content:component-scan base-package="work.chenc.*"></content:component-scan>
<!--
use-default-filters="false" 不掃描work.chenc.*的所有注解
只掃描content:include-filter 中配置的注解 這里只掃描 Controller 注解
-->
<!-- <content:component-scan base-package="work.chenc.*" use-default-filters="false">-->
<!-- <content:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>-->
<!-- </content:component-scan>-->
<!--
這里的意思是掃描所有類注解
但Controller注解的類不盡心掃描
-->
<!-- <content:component-scan base-package="work.chenc.*">-->
<!-- <content:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>-->
<!-- </content:component-scan>-->
</beans>
3、測試
@Test
public void testPerson() {
// 1党涕、獲取ApplicationContent對(duì)象解析xml文件并創(chuàng)建對(duì)象 - spring內(nèi)部處理
// 我這里bepersonbean.xml 是我對(duì)應(yīng)的xml文件的名字 也就是上面bean.xml
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:personbean.xml");
// 2烦感、獲取創(chuàng)建的對(duì)象
PersonServiceImpl personServiceimpl = context.getBean("personServiceImpl", PersonServiceImpl.class);
personServiceimpl.getPersonEntity();
}
4、執(zhí)行結(jié)果
執(zhí)行PersonServiceImpl.......
執(zhí)行了PersonEntity膛堤,姓名:張三性別:男