Spring
Spring
控制反转 Ioc , 面向切面 Aop
<?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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--bean就是java对象 , 由Spring创建和管理-->
<bean id="hello" class="com.gorilla.pojo.Hello">
<property name="name" value="Spring"/>
</bean>
</beans>
基于注解开发
@Component
@Component("user")
//相当于配置文件中的<bean id="user" class="当前注解的类">
public class User {
public String name = "zhangsan";
//@Value("zhangsan")
//public String name;
//@Value("zhangsan")
public void setName(String name) {
this.name = name;
}
}
@Component三个衍生注解
@Controller : web层
@Service : service层
@Repository : dao层
加上这些注解,就相当于这个类交给了Spring管理装配了
自动装配
@Autowired : 根据byType自动装配
//允许字段为空,默认是true,不允许
@Autowired(required = false)
@Qualifier : 不能单独使用,搭配@Autowired可以实现根据byName自动装配
@Autowired
@Qualifier(value = "bean id")
@Resource : 如果指定了name属性,则先根据该属性进行byName装配;其次进行默认的byName方式进行装配;如果都不成功,则按byType自动转配,在不成功就报错。
//如果允许对象为空,设置required = false,默认为true
@Resource(name = "bean id", required = false)
@Scope 作用域
- singleton : 默认的,Spring会采用单例模式创建这个对象。关闭工厂,所有的对象都会销毁。
- prototype : 多例模式,关闭工厂,所有的对象不会销毁。内部的垃圾回收机制会回收。
@Configuration
@Configuration //代表这是一个配置类
public class Config {
@Bean //通过方法注册一个bean,这里的返回值就是Bean的类型,方法名就是bean的id
public User user() {
return new Dog();
}
}