spring
隨著我們開發,發現了一個問題:
? ? ? ? ? ? ? ? ? ? ? ?A---->B---->C---->D
? ? ? ? ? ? ? ? ? ? ? ?在A中創建B的對象調用B的資源
? ? ? ? ? ? ? ? ? ? ? ?在B中創建C的對象調用C的資源
? ? ? ? ? ? ? ? ? ? ? ?在C中創建D的對象調用D的資源
? ? ? ? ? ? ? ? ? ? ? ?這樣的開發模式中,對象與對象之間的耦合性太高
? ? ? ? ? ? ? ? ? ? ? ?造成對象的替換非常的麻煩。
? ? ? ? ? ? ? ? ? ? ? ?A--->B2--->C--->D
解決:
? ? ? ? ? ? ? ?我們創建一個對象E,將B、C、D的示例化對象存儲到E中。然后
? ? ? ? ? ? ? ?在A中獲取E,然后通過E獲取B對象。E中存儲的對象需要動態的創建
? ? ? ? ? ? ? ?,給E配置一個文件,用該文件配置所有需要存儲在E的對的全限定路徑。
? ? ? ? ? ? ? ?然后E的底層根據配置文件中的配置信息一次性創建好存儲起來。
Spring boot
特點
1. 創建獨立的Spring應用程序
2. 嵌入的Tomcat,無需部署WAR文件
3. 簡化Maven配置
4. 自動配置Spring
5. 提供生產就緒型功能,如指標,健康檢查和外部配置
6. 絕對沒有代碼生成和對XML沒有要求配置
優點
spring boot 可以支持你快速的開發出 restful 風格的微服務架構
自動化確實方便,做微服務再合適不過了,單一jar包部署和管理都非常方便。只要系統架構設計合理,大型項目也能用,加上nginx負載均衡,輕松實現橫向擴展
spring boot 要解決的問題, 精簡配置是一方面, 另外一方面是如何方便的讓spring生態圈和其他工具鏈整合(比如redis, email, elasticsearch)
注解和實戰
@SpringBootApplication:申明讓spring boot自動給程序進行必要的配置,這個配置等同于:
@Configuration?,@EnableAutoConfiguration?和 @ComponentScan?三個配置。
@Controller:用于定義控制器類,在spring項目中由控制器負責將用戶發來的URL請求轉發到對應的服務接口(service層),一般這個注解在類中,通常方法需要配合注解@RequestMapping。
@RestController:用于標注控制層組件(如struts中的action),@ResponseBody和@Controller的合集。
@Service:一般用于修飾service層的組件
@Repository:使用@Repository注解可以確保DAO或者repositories提供異常轉譯,這個注解修飾的DAO或者repositories類會被ComponetScan發現并配置,同時也不需要為它們提供XML配置項。
@Component:泛指組件,當組件不好歸類的時候,我們可以使用這個注解進行標注。
寫bean:
public interface AlphaDao {String select();
}
@Repository("AlphaHibernate")
public class AlphaDaoHibernateImpl implements AlphaDao {@Overridepublic String select() {return "Hibernate";}
}
@Repository
@Primary
public class AlphaDaoMybatisImpl implements AlphaDao {@Overridepublic String select() {return "Mybatis";}
}
在test中通過接口類型獲取bean并使用:
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
public class CommunityApplicationTests implements ApplicationContextAware {private ApplicationContext applicationContext;@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.applicationContext=applicationContext;}@Testpublic void testApplicationContext(){System.out.println(applicationContext);AlphaDao alphaDao=applicationContext.getBean(AlphaDao.class);System.out.println(alphaDao.select());alphaDao=applicationContext.getBean("AlphaHibernate",AlphaDao.class);System.out.println(alphaDao.select());}
注意,所有bean只實例化一次,這就是所謂的單例模式了。
如果不希望單例。
加注解:
@Scope("prototype")
bean中書寫兩個方法控制初始化和銷毀時做的事:
public AlphaService() {
// System.out.println("實例化AlphaService");}@PostConstructpublic void init() {
// System.out.println("初始化AlphaService");}@PreDestroypublic void destroy() {
// System.out.println("銷毀AlphaService");}
//結果:初始化、實例化、銷毀
@Configuration:相當于傳統的xml配置文件,如果有些第三方庫需要用到xml文件,建議仍然通過@Configuration類作為項目的配置主類——可以使用@ImportResource注解加載xml配置文件。
第三方的bean:
配置
@Import:用來導入其他配置類。
import java.text.SimpleDateFormat;
@Configuration
public class AlphaConfig {@Beanpublic SimpleDateFormat simpleDateFormat(){return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");}
}
使用
@Testpublic void testBeanConfig(){SimpleDateFormat simpleDateFormat=applicationContext.getBean(SimpleDateFormat.class);System.out.println(simpleDateFormat.format(new Date()));}
依賴注入:
@AutoWired:自動導入依賴的bean。byType方式。把配置好的Bean拿來用,完成屬性、方法的組裝,它可以對類成員變量、方法及構造函數進行標注,完成自動裝配的工作。當加上(required=false)時,就算找不到bean也不報錯。
(可以寫在類前或者get前,但是一般不用)
@Qualifier:當有多個同一類型的Bean時,可以用@Qualifier(“name”)來指定。與@Autowired配合使用。@Qualifier限定描述符除了能根據名字進行注入,但能進行更細粒度的控制如何選擇候選者,具體使用方式如下:
@Autowired@Qualifier("AlphaHibernate")private AlphaDao alphaDao;@Autowiredprivate AlphaService AlphaService;@Autowiredprivate SimpleDateFormat simpleDateFormat;@Testpublic void testDI(){System.out.println(alphaDao);System.out.println(AlphaService);System.out.println(simpleDateFormat);}
經典開發三層模型:
dao:
@Repository
public class AlphaDaoHibernateImpl implements AlphaDao {@Overridepublic String select() {return "Hibernate";}
}
service:
@Service
public class AlphaService {@Autowiredprivate AlphaDao alphaDao;public String find() {return alphaDao.select();}
}
controller
@ResponseBody:表示該方法的返回結果直接寫入HTTP response body中,一般在異步獲取數據時使用,用于構建RESTful的api。在使用@RequestMapping后,返回值通常解析為跳轉路徑,加上@esponsebody后返回結果不會被解析為跳轉路徑,而是直接寫入HTTP response body中。比如異步獲取json數據,加上@Responsebody后,會直接返回json數據。該注解一般會配合@RequestMapping一起使用。
@RequestMapping:提供路由信息,負責URL到Controller中的具體函數的映射。
@Controller
@RequestMapping("/alpha")
public class AlphaController {@Autowiredprivate AlphaService AlphaService;@RequestMapping("data")@ResponseBodypublic String getData(){return AlphaService.find();}
springMVC
原始請求響應
@RequestMapping("/http")public void http(HttpServletRequest request, HttpServletResponse response){System.out.println(request.getMethod());System.out.println(request.getServletPath());Enumeration<String> enumeration=request.getHeaderNames();while(enumeration.hasMoreElements()){String name=enumeration.nextElement();String value=request.getHeader(name);System.out.println(name+":"+value);}System.out.println(request.getParameter("code"));response.setContentType("text/html;charset=utf-8");try(PrintWriter writer = response.getWriter()){writer.write("<h1>橙白站</h1>");} catch (IOException e) {e.printStackTrace();}}
get
//get// /students?current=1&limit=20@RequestMapping(path="/students",method= RequestMethod.GET)@ResponseBodypublic String getStudents(
//默認@RequestParam(name="current",required = false,defaultValue = "1") int current,@RequestParam(name="limit",required = false,defaultValue = "10") int limit){System.out.println(current);System.out.println(limit);return "some students";}// /student/123@RequestMapping(path="/student/{id}",method= RequestMethod.GET)@ResponseBodypublic String getStudent(@PathVariable("id") int id){System.out.println(id);return "a student";}
post
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>增加學生</title>
</head>
<body><form method="post" action="/community/alpha/student"><p>姓名:<input type="text" name="name"></p><p>年齡:<input type="text" name="age"></p><p><input type="submit" value="保存"></p></form>
</body>
</html>
//post@RequestMapping(path = "/student",method = RequestMethod.POST)@ResponseBodypublic String saveStudent(String name,int age){System.out.println(name);System.out.println(age);return "success";}
響應
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>Teacher</title>
</head>
<body><p th:text="${name}"></p><p th:text="${age}"></p>
</body>
</html>
//響應html數據@RequestMapping(path = "/teacher",method = RequestMethod.GET)public ModelAndView getTeacher(){ModelAndView mav=new ModelAndView();mav.addObject("name","張三");mav.addObject("age",30);mav.setViewName("/demo/view");return mav;}//返回模板的地址@RequestMapping(path = "/school",method = RequestMethod.GET)public String getSchool(Model model){model.addAttribute("name","北大");model.addAttribute("age","100");return "/demo/view";}
異步
//響應json數據(異步請求中)//java對象->json字符串-> js對象@RequestMapping(path = "/emp",method = RequestMethod.GET)@ResponseBodypublic Map<String,Object> getEmp(){Map<String,Object> emp=new HashMap<>();emp.put("name","張三");emp.put("age",23);emp.put("salary",8000.00);return emp;}
@RequestMapping(path = "/emps",method = RequestMethod.GET)@ResponseBodypublic List<Map<String,Object>> getEmps(){List<Map<String,Object>> list=new ArrayList<>();Map<String,Object>emp=new HashMap<>();emp.put("name","張三");emp.put("age",23);emp.put("salary",8000.00);list.add(emp);emp=new HashMap<>();emp.put("name","李四");emp.put("age",24);emp.put("salary",9000.00);list.add(emp);return list;}
?
其他注解
@EnableAutoConfiguration:SpringBoot自動配置(auto-configuration):嘗試根據你添加的jar依賴自動配置你的Spring應用。例如,如果你的classpath下存在HSQLDB,并且你沒有手動配置任何數據庫連接beans,那么我們將自動配置一個內存型(in-memory)數據庫”。你可以將@EnableAutoConfiguration或者@SpringBootApplication注解添加到一個@Configuration類上來選擇自動配置。如果發現應用了你不想要的特定自動配置類,你可以使用@EnableAutoConfiguration注解的排除屬性來禁用它們。
@ComponentScan:表示將該類自動發現掃描組件。個人理解相當于,如果掃描到有@Component、@Controller、@Service等這些注解的類,并注冊為Bean,可以自動收集所有的Spring組件,包括@Configuration類。我們經常使用@ComponentScan注解搜索beans,并結合@Autowired注解導入。可以自動收集所有的Spring組件,包括@Configuration類。我們經常使用@ComponentScan注解搜索beans,并結合@Autowired注解導入。如果沒有配置的話,Spring Boot會掃描啟動類所在包下以及子包下的使用了@Service,@Repository等注解的類。
@ImportResource:用來加載xml配置文件。
@Bean:用@Bean標注方法等價于XML中配置的bean。
@Value:注入Spring boot application.properties配置的屬性的值。示例代碼:
@Inject:等價于默認的@Autowired,只是沒有required屬性;
@Bean:相當于XML中的,放在方法的上面,而不是類,意思是產生一個bean,并交給spring管理。
@Resource(name=”name”,type=”type”):沒有括號內內容的話,默認byName。與@Autowired干類似的事。