标签:factory import pos package 必须 oid inter struct lap
spring中ioc的常用注解
<bean id="accountService" class="com.mantishell.service.impl.AccountServiceImpl"
scope="" init-method="" destroy-method="">
<property name="" value="" | ref=""/>
</bean>
用于创建对象,作用和
注意使用注解,需要把配置文件中头部信息更换为:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--告知spring在创建容器时要扫描的包,配置所需要的标签不是在beans的约束中,而是一个名称为
context名称空间和约束中-->
<context:component-scan base-package="com.mantishell"/>
</beans>
持久层
IAccountDao.java
package com.mantishell.dao;
public interface IAccountDao {
void saveAccount();
}
AccountDaoImpl.java
package com.mantishell.dao.impl;
import com.mantishell.dao.IAccountDao;
import org.springframework.stereotype.Repository;
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
public void saveAccount() {
System.out.println("保存了账户");
}
}
业务层
IAccountService.java
package com.mantishell.service;
public interface IAccountService {
void saveAccount();
}
AccountServiceImpl.java
package com.mantishell.service.impl;
import com.mantishell.dao.IAccountDao;
import com.mantishell.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao = null;
public void saveAccount() {
accountDao.saveAccount();
}
}
表现层
package com.mantishell.ui;
import com.mantishell.service.IAccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* 模拟一个表现层,用于调用业务层
*/
public class Client {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
IAccountService as = (IAccountService) ac.getBean("accountService");
as.saveAccount();
}
}
用于注入数据
作用和xml配置文件中的bean标签中写的
@Autowired
@Qualifier("accountDao1")//指定使用id=accountDao1的bean对象
private IAccountDao accountDao = null;
或者
@Resource(name="accountDao2")//指定使用id=accountDao2的bean对象
private IAccountDao accountDao = null;
改变作用范围
作用和bean标签中scope属性功能相同,常用取值:singleton prototype
@Scope("singleton")
public class AccountServiceImpl implements IAccountService {
作用和bean标签中的init-method和destroy-methode一样
PreDestroy:用于指定销毁方法
PostConstruct:用于指定初始化方法
@PostConstruct
public void init(){
System.out.println("初始化方法执行了");
}
@PreDestroy
public void destroy(){
System.out.println("销毁方法执行了");
}
标签:factory import pos package 必须 oid inter struct lap
原文地址:https://www.cnblogs.com/mantishell/p/12557867.html