Spring简单介绍(二)之IOC常用的注解

本文以实现账户CRUD为例,介绍Spring中基于配置文件和注解的IOC配置。基于配置文件可将实现类装配到IOC容器,通过标签注入对象;基于注解则介绍了常用的18个注解,如装配bean、属性注入、配置类等注解,还给出纯注解demo及Spring与Junit整合注解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这篇博文主要使用了一个列子,介绍了基于配置文件的IOC配置和基于注解的IOC配置。
要求:实现账户的CRUD
环境搭建:
数据库、依赖省略。。。。。。

//实体类
public class Account {
    private Integer id;
    private String name;
    private Float money;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Float getMoney() {
        return money;
    }
    public void setMoney(Float money) {
        this.money = money;
    }
    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

//创建service接口和实现类

public interface IAccountService {
    void saveAccount(Account account);
    void updateAccount(Account account);
    void deleteAccountById(Integer accountId);
    Account queryAccountById(Integer accountId);
    List<Account> queryAccountList();
}
public class AccountServiceImpl implements IAccountService {

    private IAccountDao accountDao;

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }

    @Override
    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }

    @Override
    public void deleteAccountById(Integer accountId) {
        accountDao.deleteAccountById(accountId);
    }

    @Override
    public Account queryAccountById(Integer accountId) {
        return accountDao.queryAccountById(accountId);
    }

    @Override
    public List<Account> queryAccountList() {
        return accountDao.queryAccountList();
    }
}

//创建dao的接口和实体类

public interface IAccountDao {
    void saveAccount(Account account);
    void updateAccount(Account account);
    void deleteAccountById(Integer accountId);
    Account queryAccountById(Integer accountId);
    List<Account> queryAccountList();
}
public class AccountDaoImpl implements IAccountDao {
    private JdbcTemplate jdbcTemplate;
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public void saveAccount(Account account) {
        jdbcTemplate.update("insert into account values(null,?,?)",account.getName(),account.getMoney());
    }
    @Override
    public void updateAccount(Account account) {
        jdbcTemplate.update("update account set money = ? where id = ?",account.getMoney(),account.getId());
    }
    @Override
    public void deleteAccountById(Integer id) {
        jdbcTemplate.update("delete from account where id = ?",id);
    }
    @Override
    public Account queryAccountById(Integer id) {
        return jdbcTemplate.queryForObject("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),id);
    }
    @Override
    public List<Account> queryAccountList() {
        return jdbcTemplate.query("select * from account",new BeanPropertyRowMapper<Account>(Account.class));
    }
}

一、基于配置文件的IOC配置

<?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">
 <!--加载外部资源文件-->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
   <!-- 配置注解扫描的包:声明到指定的包下去进行扫描,如果发现类上有对应的注解,将其装配到容器中 -->
    <context:component-scan base-package="cn.itcast"></context:component-scan>
    
    <bean id="accountService" class="cn.itcast.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>
    <bean id="accountDao" class="cn.itcast.dao.impl.AccountDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <constructor-arg index="0" ref="dataSource"></constructor-arg>
    </bean>
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClass}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
</beans>

从上述案例中我们发现:
1、 通过配置文件可以将service和dao的实现类装配到IOC容器中
2、 通过bean标签中的property标签配置属性的setter方法可以将IOC容器中的一个对象注入到容器中的另外一个对象中。
3、只要一个普通类的全限定类名,就可以由spring来创建该对象装配到IOC容器中。

二、基于注解的IOC配置

2.1 IOC常用的IOC注解(18个)
1)四个装配bean对象的注解
@Component------装配三层以外的注解
@Controller-------用于表现层
@Service-----用于业务层
@Repository----用于持久层
2)四个属性注入的注解
@Autowired:
自动按照类型注入。当使用注解注入属性时,set方法可以省略。它只能注入其他bean类型。当有多个类型匹配时,使用要注入的对象的变量名称作为bean的id,在spring容器查找,找到了也可以注入成功。找不到就报错。
@Qualifier
在自动按照类型注入的基础之上,再按照Bean的id注入。它在给字段注入时不能独立使用,必须和@Autowire一起使用;但是给方法参数注入时,可以独立使用。
@Resource
直接按照Bean的id注入。它也只能注入其他bean类型。
@Value
注入基本数据类型和String类型数据的 ,不能注入bean类型的
3)一个Scope作用范围的注解 用于指定bean的作用域,一般就是singleton和prototype
在这里插入图片描述
4)两个生命周期相关的注解
@PostConstruct:作用: 用于指定初始化方法。相当于bean标签中的init-method属性。
@PreDestroy 作用: 用于指定销毁方法。相当于bean标签中的destroy-method属性

5)五个配置类的注解
@Configuration 声明一个类为配置类,用于替代applicationContext.xml的。
@ComponentScan 用于开启注解扫描
@PropertySource 用于加载配置资源文件
@Bean 该注解只能写在方法上,将方法的返回值作为一个bean,并且放入spring容器。
@Import :导入其他的配置类

2.2纯注解的demo(使用了配置类,没有applicationContext配置文件)

@Configuration//声明这是一个配置类,用来代替xml的
@ComponentScan("cn.itcast")//开启注解扫描
@Import(value={JdbcConfig.class})
public class SpringConfiguration {


}

//加载外部资源文件
@PropertySource(value = {"classpath:jdbc.properties"})
public class JdbcConfig {

    @Value("${jdbc.driverClass}")
    private String driverClassName;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;


    @Bean(name="jdbcTemplate")
    public JdbcTemplate createJdbcTempalte(@Qualifier("dataSource") DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }

    @Bean(name="dataSource")
    public DataSource createDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
}

6)两个Spring的test整合Junit相关的
@RunWith 替换掉junit的运行器,换成一个可以初始化spring容器的运行器
@ContextConfiguration 加载配置类或者xml配置文件

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class AccountControllerTest {
    @Autowired
    private AccountController accountController;
    @Test
    public void saveAccuont() {

        Account account = new Account();
        account.setName("admin13");
        account.setMoney(1000f);

        accountController.saveAccuont(account);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值