Spring使用注解开发
导包
设置注解扫描范围
<context:component-scan base-package="com.tl"/>
使用注解完成依赖注入
注解注入不需要set方法
配置
<?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
https://www.springframework.org/schema/context/spring-context.xsd">
<!--设置注解扫描范围-->
<context:component-scan base-package="com.tl"/>
<!--开启注解-->
<context:annotation-config/>
</beans>
实体类
People
package com.tl.pojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @author tl
*/
@Component
public class People {
@Value("tl")
private String name;
@Autowired
private Dog dog;
@Autowired
private Cat cat;
public People() {
}
public String getName() {
return name;
}
public Dog getDog() {
return dog;
}
public Cat getCat() {
return cat;
}
}
Cat
package com.tl.pojo;
import org.springframework.stereotype.Component;
/**
* @author tl
*/
@Component
public class Cat {
public void shout(){
System.out.println("喵~");
}
}
Dog
package com.tl.pojo;
import org.springframework.stereotype.Component;
/**
* @author tl
*/
@Component
public class Dog {
public void shout(){
System.out.println("汪~");
}
}
测试类
从Spring容器中取对象时,根据对象类名来取。
import com.tl.pojo.People;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author tl
*/
public class Test {
@org.junit.Test
public void test1(){
ApplicationContext context =
new ClassPathXmlApplicationContext("beans.xml");
People people = (People) context.getBean("people");
people.getCat().shout();
people.getDog().shout();
}
}
使用注解注入属性
Spring 的开发规范
1.
1.
1. xml用来管理bean;
2.
2.
2. 注解只负责完成属性的注入。
衍生注解
对应MVC三层架构
本质还是@Component。
dao 【@Repository】
service 【@Service】
controller 【@Controller】