Spring基础配置
Spring框架四大原则:
- 使用POJO进行轻量级和最小侵入式开发。
- 通过依赖注入和基于接口编程实现松耦合。
- 通过AOP和默认习惯进行声明式编程。
- 使用AOP和模板(template)减少模式化代码。
Spring所有功能的设计和实现都是基于此四大原则。
依赖注入(DI)
依赖注入就是让容器来负责创建对象和维护对象间的依赖关系,Spring 把相互协作的关系称为依赖关系,比如A调用了B的方法,则A依赖于B。依赖注入上午主要目的是为了解耦,体现了一种“组合”的方式。
容器则是Spring IoC容器(ApplicationContext),由容器负责创建bean,并且通过容器将功能类Bean注入到你需要的Bean中。Spring中提供使用xml,注解,Java配置,groovy配置实现Bean的创建和注入。
无论是xml配置、注解还是Java配置,都被称为配置元数据。元数据本身不具备任何执行能力。由Spring容器对这些配置元数据解析后执行操作,进行Bean初始化、配置和管理依赖。
声明bean的注解:
- @Component组件,没有明确的角色。
- @Service在业务逻辑层(Service层)使用。
- @Repository在数据访问层(dao层)使用。
- @controller在展现层(MVC→Spring MVC)使用。
注入bean的注解,一般情况下通用。
- @Autowired:String提供的注解。
- @Inject:JSR-330提供的注解。
- @Resource:JSRP250提供的注解。
代码示例:
编写功能类的Bean
package com.cqvie.spring4.di;
import org.springframework.stereotype.Service;
@Service //使用Service注解声明当前FunctionService类是Spring管理的一个Bean
public class FunctionService {
public String sayHello(String word) {
return "Hello" + word + "!";
}
}
使用功能类的Bean
package com.cqvie.spring4.di;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service // 使用@Service注解声明当前UseFunctionService类是Spring管理的一个Bean
public class UserFunctionService {
@Autowired // 使用Autowried将FunctionService的实体Bean注入到UserFunctionService中,让UserFunctionService具备Function中的功能
FunctionService functionService;
public String SayHello(String word){
return functionService.sayHello(word);
}
}
配置类
package com.cqvie.spring4.di;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration // @Configuration声明当前类是一个配置类
@ComponentScan("com.cqvie.spring4.di") // 使用@ComponentScan注解自动扫描包名下的所有使用@Service、@Component、@Repository和@Controller的类,并注册为Bean
public class DiConfig {
}
运行
package com.cqvie.spring4.di;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DiConfig.class);// 使用AnnotationConfigApplicationContext作为容器,接受输入一个配置类作为参数
UserFunctionService userFunctionService=context.getBean(UserFunctionService.class);//获得声明配置的UserFunctionService的Bean
System.out.println(userFunctionService.SayHello("world"));
context.close();
}
}
运行结果