配置好aop beans context 4.2的xsl
@Scope:控制是否以单例的形式产生对象
@Component(修饰控制层)下分为@Controller、@Service、@Repository,效果一样
@Controller:修饰控制层
@Service:修饰业务层,将业务层对象的创建交给spring容器
@Repository:修饰DAO层,将DAO层对象的创建交给spring容器
用了这几个,后面的括号都不用写了。
DAO层:
package cn.java.annotationioc; import org.springframework.stereotype.Component; import org.springframework.stereotype.Repository; @Repository public class FrontDaoImpl { public void addUser() { System.out.println("添加成功"); } }
Service层:
package cn.java.annotationioc; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class FrontServiceImpl { @Autowired private FrontDaoImpl fdi; public void userAdd() { fdi.addUser(); } }
Servlet层:
package cn.java.annotationioc; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component("frontServlet") public class FrontServlet { @Autowired private FrontServiceImpl fsi; public void doGet() { fsi.userAdd(); } }
主层:
package cn.java.annotationioc; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Window { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); FrontServlet fs = (FrontServlet) context.getBean("frontServlet"); fs.doGet(); } }
主xml:
<?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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"> <context:component-scan base-package="cn.java."></context:component-scan> </beans>