0%

核心基础

基于XML使用、基于注解+XML混合使用、基于纯注解使用

1.基于XML使用

1.IoC配置

配置被Spring容器管理的bean信息,默认使用无参构造方法。

bean标签实例化三种方式:

  1. 无参构造(常用)

    1
    <bean id = "userService" class = "com.xiaoruiit.service.UserServiceImpl"></bean>
  2. 静态工厂

  3. 实例工厂

2.DI配置

给bean的属性赋值

  1. 构造函数注入,constructor-arg标签

    1
    2
    3
    4
    <bean id="userService" class="com.xiaoruiit.service.UserServiceImpl">
    <constructor-arg name="id" value="1"></constructor-arg>
    <constructor-arg name="name" value="zhangsan"></constructor-arg>
    </bean>
  2. set方法注入,property标签

    1
    2
    - 需要配置bean标签的子标签property
    - 需要配置的bean中指定setter方法。

2.基于注解+XML混合使用

使用xml的地方:1.xml配置文件,内容包括:扫描包,配置数据源;2.加载配置文件。

使用注解的地方:

IoC注解的使用方法

  1. xml配置 context:component-scan标签

    1
    <context:component-scan base-package="com.xiaoruiit.service"></context:component-scan>
  2. 类上添加注解@Component @Controller @Service @Repository

    @Component:把类交给Spring容器管理。

    @Controller @Service @Repository:@Component的延伸,为了方便标注表现层、业务层、持久层,乱写不影响使用,影响理解。

    1
    2
    3
    4
    @Service
    public class UserServiceImpl implements UserService {

    }

DI的注解

  • @Autowired

    • 默认按类型装配(byType)
    • spring自带的注解
    • 找不到时会报错,如果需要允许null值,可以设置它的required属性为false,如:@Autowired(required=false)
    • 如果我们想按名称装配(byName)可以结合 @Qualifier 注解进行使用
  • @Qualifier

    • 在给字段注入时不能独立使用,必须和@Autowire 一起使用;
  • @Resource

    • 默认按名称装配(byName)
    • 属于J2EE JSR250规范的实现 ,jdk的注解
    • 推荐使用@Resource注解
  • @Inject

    • 根据类型进行自动装配的,如果需要按名称进行装配,则需要配合@Named;
    • 是JSR330中的规范,需要导入javax.inject.Inject
    • 可以作用在变量、setter方法、构造函数上。
  • @Value

    • 给基本类型和String类型注入值

    • 可以使用占位符获取属性文件中的值

      1
      2
      @Value(“${name}”)//name是properties文件中的key
      private String name;
  • @Scope

    • 指定 bean 的作用范围
    • 属性: value:指定范围的值。取值:singleton(默认,单例) prototype(原型,多例) request session globalsession

3.基于纯注解使用

将“基于注解+XML混合使用”中的xml部分使用注解实现。

xml实现的部分

1.扫描包

1
2
3
<!-- 开启注解并扫描指定包中带有注解的类 -->
<context:component-scan base-package="com.xiaoruiit.service"/>
<context:property-placeholder src=""></context:property-placeholder>

2.非自定义Bean

1
2
3
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" value="dataSource"></property>
</bean>

3.加载配置文件

1
ApplicationContext context = new ClassPathXmlApplicationContext(“beans.xml”);

使用注解实现

1.xml扫描包

@Configuration 相当于xml配置文件

1
2
3
4
5
6
7
@Configuration
public class SpringConfiguration {
//spring容器初始化时,会调用配置类的无参构造函数
public SpringConfiguration(){
System.out.println(“容器启动初始化。。。”);
}
}

@ComponentScan

1
2
3
相当于context:component-scan标签
组件扫描器,扫描@Component、@Controller、@Service、@Repository注解的类。
该注解是编写在类上面的,一般配合@Configuration注解一起使用。
1
2
3
4
5
6
7
8
9
10
11
12
@Configuration
@ComponentScan(basePackages="com.xiaoruiit.service")
public class SpringConfiguration {
public SpringConfiguration() {
System.out.println("容器初始化...");
}
// @Bean
// @Scope("prototype")
// public UserService userService() {
// return new UserServiceImpl(1,"张三");
// }
}

2.非自定义Bean

@Bean (@value)

1
2
3
4
5
6
相当于<bean>标签
作用为:注册bean对象,主要用来配置非自定义的bean,比如DruidDataSource、SqlSessionFactory
@Bean标注在方法上(返回某个实例的方法)
name:给当前@Bean 注解方法创建的对象指定一个名称(即 bean 的 id)。如果不指定,默认与标注的方法名相
同。
@Bean注解默认作用域为单例singleton作用域,可通过@Scope(“prototype”)设置为原型作用域;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Configuration
public class SpringConfiguration {
//spring容器初始化时,会调用配置类的无参构造函数
public SpringConfiguration(){
System.out.println(“容器启动初始化。。。”);
}

@Bean
@Scope(“prototype”)
public SqlSessionFactory userService(){
SqlSessionFactory sqlSessionFactory = new DefaultSqlSessionFactory();
sqlSessionFactory.setxxx();
return sqlSessionFactory;
}

@Bean
@Scope(“prototype”)
public SqlSessionFactory userService(){
SqlSessionFactory sqlSessionFactory = new DefaultSqlSessionFactory();
sqlSessionFactory.setxxx();
return sqlSessionFactory;
}
}

@PropertySource

解决properties文件:

1
2
3
4
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///spring
jdbc.username=root
jdbc.password=123456
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@Configuration
@PropertySource("classpath:jdbc.properties")
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
/**
* 创建一个数据源,并存入 spring 容器中
* *
@return
*/
@Bean(name = "dataSource")
public DataSource createDataSource() {
try {
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass(driver);
ds.setJdbcUrl(url);
ds.setUser(username);
ds.setPassword(password);
return ds;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

3.加载配置文件

@Import

1
2
相当于spring配置文件中的<import>标签
用来组合多个配置类,在引入其他配置类时,可以不用再写@Configuration 注解。当然,写上也没问题。
1
2
3
4
5
6
7
8
9
10
@Configuration
@ComponentScan(basePackages = "com.kkb.spring")
@Import({ JdbcConfig.class })
public class SpringConfiguration {
}

@Configuration
@PropertySource("classpath:jdbc.properties")
public class JdbcConfig {
}

创建纯注解方式上下文容器

1
2
3
4
ApplicationContext context = new
AnnotationConfigApplicationContext(SpringConfiguration.class);
UserService service = context.getBean(UserService.class);
service.saveUser();