注解寫法:@注解名稱(屬性名=屬性值)
注解使用在類、方法佑力、屬性上面
spring注解開發(fā)準(zhǔn)備
1.導(dǎo)入jar包(最基礎(chǔ)jar包和spring-aop.jar)
2.創(chuàng)建類和方法
3.創(chuàng)建spring配置文件(bean.xml)式散,引入約束(。打颤。杂数。spring-context.xsd)
4.<!--開啟注解掃描-->
<context:component-scan base-package="包名1,包名2"></context:component-scan>
<!--到包里面掃描類瘸洛、方法揍移、屬性上面是否有注解-->
<!--掃描屬性上的注解-->
<context:annoation-config></context:annoation-config>
創(chuàng)建注解對(duì)象
@Component組件(作用在類上)
@Component(value="user")//<bean id="user" class=""/>
public class User{...}
ApplicationContext context = ClassPathXmlApplicationContext("applicationContext.xml");
User user = context.getBean("user");
Component的三個(gè)衍生注解(功能來講目前是一致的,都創(chuàng)建對(duì)象)
@Controller:控制層
@Service:業(yè)務(wù)層
@Repository:持久層
這三個(gè)注解是為了讓標(biāo)注類本身的用途清晰反肋,spring在后續(xù)版本對(duì)其增強(qiáng)
創(chuàng)建對(duì)象是單例還是多實(shí)例
@Scpoe(value="prototype")
注解注入屬性(對(duì)象類型)
@Autowired
public User user;
//在屬性上使用注解那伐,完成對(duì)象注入,使用注解是不需要set方法的
@Resource(name="user");//name屬性值:注解創(chuàng)建dao對(duì)象的value值(可以準(zhǔn)確指定)
配置文件和注解混合使用
1.創(chuàng)建杜希昂操作使用配置文件方式實(shí)現(xiàn)
2.注入屬性的操作使用注解方式實(shí)現(xiàn)