JAVA架构(四)------全注解SpringMvc

⦁    全注解下的Spring IoC
在Spring Boot中,我们主要通过注解来装配Bean到Spring IoC容器中,为了贴近Spring Boot的需要,我们需要介绍一个基于注解的IoC容器,它就是AnnotationConfigApplicationContext.    Spring boot装配和获取Bean的方法和它是差不多的。
⦁    最简单的方式装配bean
⦁       User.java
   public class User {

    private Long id;
    private String userName;
    private String note;
    
}
⦁    定义java配置文件

@Configuration
public class AppConfig {
    @Bean(name = "user")
    public User initUser() {
        User user = new User();
        user.setId(1L);
        user.setUserName("user_name_1");
        user.setNote("note_1");
        return user;
    }

}
注意:@Configuration 代表这是一个Java配置文件,Spring 容器会根据它来生成IoC容器来装配Bean
@Bean 代表initUser方法返回的对象装配到IoC容器中,如果没设置name属性,则使用方法名,作为Bean的名称
⦁    构建容器
public class Main {
    public static void main(String[] args) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
        User user = ctx.getBean(User.class);
        System.out.println(user.getUserName());
    }
}

⦁    通过扫描装配Bean
⦁    加入注解@Compoent
   @Component("user")
public class User {
    @Value("1")
    private Long id;
    @Value("user_name_110")
    private String userName;
    @Value("note_1")
    private String note;
}
注意:@Component 如果不配置内容,则使用类名首字母小写,其他不变来作为Bean的名称
⦁    加入注解@ComponentScan
   @Configuration
   @ComponentScan
   public class AppConfig{}
   注意:它只会扫描类AppConfig所在的当前包和其子包
    想要排除扫描的话:@ComponentScan(excludeFilters = { @Filter(classes = { Service.class }) })
⦁       测试扫描
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
        User user = ctx.getBean(User.class);
        System.out.println(user.getUserName());

⦁    自定义第三Bean
比如:想要引入DBCP数据源
定义DBCP数据源依赖
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
  使用DBCP生产数据源
    @Configuration
@ComponentScan(excludeFilters = { @Filter(classes = { Service.class }) })
public class AppConfig {
    @Bean(name = "dataSource")
    public DataSource getDataSource() {
        Properties props = new Properties();
        props.setProperty("driver", "com.mysql.jdbc.Driver");
        props.setProperty("url", "jdbc:mysql://localhost:3306/springboot");
        props.setProperty("username", "root");
        props.setProperty("password", "1234");
        DataSource dataSource = null;
        try {
            dataSource = BasicDataSourceFactory.createDataSource(props);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return dataSource;
    }

}
这样就能将第三方包的类装配到Spring IoC容器中了
⦁    依赖注入
⦁      常见的依赖注入注解
  @Autowired: 根据属性的类型(by type) 找到对应的Bean进行注入。
  消除歧义性的注解   @Primary 和@Quelifier
 @Primary :告诉Spring IoC容器,当发现有多个同样类型的Bean时,请优先使用我进行注入。
 @Quelifier通过名称进行注入
⦁    使用属性文件
    1.属性文件依赖
    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
   </dependency>
    
⦁    在application.properties文件中添加如下配置
database.driverName=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/springboot
database.username=root
database.password=1234

⦁    使用属性配置
  package com.springboot.mvc.pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class DataBaseProperties {
    @Value("${database.driverName}")
    private String driverName = null;
    @Value("${database.url}")
    private String url = null;

    private String username = null;

    private String password = null;

    public String getDriverName() {
        return driverName;
    }

    public void setDriverName(String driverName) {
        this.driverName = driverName;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    @Value("${database.username}")
    public void setUsername(String username) {
        System.out.println(username);
        this.username = username;
    }
    @Value("${database.password}")
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}
启动Spring Boot就可以看到,完成属性的读取

有时候也可以使用@ConfigurationProperties,减少配置
 @Component
@ConfigurationProperties("database")
public class DataBaseProperties {
    private String driverName = null;

    private String url = null;
    private String username = null;

    private String password = null;

    public String getDriverName() {
        return driverName;
    }

    public void setDriverName(String driverName) {
        System.out.println(driverName + "-------------");
        this.driverName = driverName;
    }

    public String getUrl() {

        return url;
    }

    public void setUrl(String url) {
        System.out.println(url + "---------");
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
这里注解@ConfigurationProperties中配置的字符串database,将于POJO的属性名称,组成属性的全限定名去配置文件里查找,这样就能将对应的属性读到POJO中了
但是如果将所有的内容都配置到application.properties中,不太方便,我们可以使用新的属性文件。如将application.properties关于数据库的配置信息迁移到jdbc.properties中
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.PropertySource;

@SpringBootApplication
@PropertySource(value = { "classpath:jdbc.properties" }, ignoreResourceNotFound = true)
public class SpringbootMvc2Application {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootMvc2Application.class, args);
    }
}
⦁    引入XML配置bean
尽管Spring boot建议使用注解和扫描配置Bean,但同样地,它不拒绝使用XML配置Bean,我们也可以在Spring boot中使用XML对Bean配置,这里需要使用的注解是@ImportResource,通过它可以引入
对应的XML文件,用来加载Bean。有时候有些框架(如Dubbo)是基于Spring的XML方式进行开发的,这时候需要引入XML实现配置。
⦁    定义一个POJO
       public class Person {
    private String username;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}
⦁    使用XML配置POJO—spring-other.xml
<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 id="person" class="com.springboot.mvc.pojo.Person"/>
</beans>
     3.装配XML定义的Bean
@SpringBootApplication
@PropertySource(value = { "classpath:jdbc.properties" }, ignoreResourceNotFound = true)
@ImportResource(value = "classpath:spring-other.xml")
public class SpringbootMvc2Application {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootMvc2Application.class, args);
    }

    @Autowired
    private Person person;

}

猜你喜欢

转载自blog.csdn.net/LRXmrlirixing/article/details/82461007
今日推荐