欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring基础

程序员文章站 2022-07-11 13:55:57
...
spring框架本身四大原则:
     1.使用pojo进行轻量级和最小侵入式开发
     2.通过依赖注入和基于接口编程实现松耦合
     3.通过Aop和默认习惯进行声明式编程
     4.使用Aop和模板减少模式化代码

声明Bean的注解(声明当前的bean有spring容器管理的一个bean)
    @Compent组件,没有明确的角色
    @Service在业务逻辑层(service层) 使用
    @Repository 在数据访问层(dao层)使用
    @Controller 在表现层(spring mvc) 使用

注入Bean的注解(可注解 在set方法或者属性上面  习惯是注解在属性上)
     @Autowired:spring 提供的注解
      @Inject:JSR-330提供的注解
      @Resource:JSR-250提供的注解

@Configuration声明当前类是一个配置类
@CompanentScan(“”)将自动扫描包名下所有使用上面声明注解的类,并注册为Bean


Java配置:
     spring 4.x推荐的配置 可以完全替代xml配置 ,通过@Configuration和 @Bean 来实现
     @Configuration 声明当前的类是一个配置类 相当于 spring配置的xml文件
     @Bean 注解在方法上面  声明当前方法的返回值 为一个Bean


public class FunctionService {
    public String sayHello(String word){
        return "hello " + word + " !";
    }
}

public class UseFunctionService {
    @Autowired
    private FunctionService functionService;

    public String sayHello(String word){
        return functionService.sayHello(word);
    }
}

@Configuration
public class JavaConfig {
    @Bean
    public FunctionService functionService() {
        return new FunctionService();
    }
    @Bean(initMethod="init",destroyMethod="destroy")
    public UseFunctionService useFunctionService(){
        return new UseFunctionService();
    }
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext(JavaConfig.class);
        UseFunctionService service = context.getBean(UseFunctionService.class);
        String res = service.sayHello("young");
        System.out.println(res);
        context.close();
    }
}


Bean 的Scope: Spring默认的配置是全容器共享一个实例
通过 @Scope注解来实现:
          1.Singleton  只有一个Bean实例
          2.Prototype:每次调用新建一个实例
          3.Request:web项目中为每一个 http request 新建一个bean实例
          4.Session:Web项目中为每一个 http session 新建一个Bean实例
          5.GlobalSession:  @StepScope


spring的El表达式:
    通过@Value注解使用
         包括 注入普通的字符;注入系统属性;注入表达式运算结果;注入其他bean属性;注入文            件内容 ;注入网址 内容;注入属性文件

通过 @PropertySource("classpath:a.properties") 使用配置文件

@Value("t love you")
private String normalStr;

@Value("#{systemProperties['os.name']}")
private String osName;

@Value("#{demoService.anther}")
private String normalStr;

@Value("${user.name}")
private String username;